缩放或按比例调整从图库中选取的图像

时间:2017-03-25 19:42:53

标签: java android bitmap

在我的应用程序中,我需要从图库中选择图像到我的ImageView。如果我选择简单的图像,例如,从互联网上下载,它工作正常。但如果我选择在手机上制作的照片,我会W/OpenGLRenderer: Bitmap too large to be uploaded into a texture (4160x3120, max=4096x4096)

使用Glide加载照片会给出

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

这是我的代码,它会拾取图像并从中创建一个位图。

@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();
    }
}

如果图像太大,我该如何缩放图像呢?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容来压缩位图,这里bitmapImage是您的位图对象。 :

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);