简体   繁体   中英

Scaling or proportionally resizing image picked from the gallery

In my app i need to pick image from gallery to my ImageView. If I pick simple image, for example, downloaded from the Internet, it works fine. But if i pick photo made on my phone i get W/OpenGLRenderer: Bitmap too large to be uploaded into a texture (4160x3120, max=4096x4096)

Using Glide to load the photo gives this

Caused by: java.lang.IllegalArgumentException: Unknown type class android.graphics.Bitmap. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class

This is my code which picks up an image and creates a bitmap out of it.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // When an Image is picked
    if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK
            && null != data) {

        Uri imageUri = data.getData();
        InputStream inputStream;
        try {
            inputStream = getContentResolver().openInputStream(imageUri);
            Bitmap image = BitmapFactory.decodeStream(inputStream);
            commentImage = (ImageView) findViewById(R.id.comment_image);
            //Glide.with(this).load(image).asBitmap().override(4095, 4095).into(commentImage);
            commentImage.setImageBitmap(image);
            //commentImage.setImageBitmap(Bitmap.createScaledBitmap(image, 4095, 2048, false));
            Toast.makeText(this, "SUCCESS", Toast.LENGTH_LONG).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            // show a message to the user indictating that the image is unavailable.
            Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
        }

    } else {
        Toast.makeText(this, "You haven't picked Image",
                Toast.LENGTH_LONG).show();
    }
}

How can I scale an Image in case if it is too big?

You can use the following to compress the bitmap, here bitmapImage is your bitmap object. :

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmapImage.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);  //90 refers to 90% quality, or 10% compression
        byte[] data = byteArrayOutputStream.toByteArray();

Bitmap compressedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM