开发者

Problems with scaling image to thumbnail size and load in imageview to save memory

I am trying to scale my images down to smaller size I was loa开发者_运维技巧ding them as they were into an imageview and I started getting a "bitmap size exceeds VM budget" exception. On the other hand if I get the thumbnails instead of the actual images and show them it runs smooth. But I need the URIs of the actual images for later use which I can't get if I straight away load the thumbnails.

After looking around, I found a way, but it's not working.

Code:

Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, name);
uriList.add(uri.getPath());

File image = new File(uri.getPath());

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap actualBitmap = BitmapFactory.decodeFile(image.getPath(), options);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(actualBitmap, image_width, image_height, false);
iv.setImageBitmap(scaledBitmap);

The part where I get the actualBitmap returns null, and so the imageview is empty. If I print uri.getpath() it gives:

/external/images/media//sdcard/dcim/Camera/imagename.jpg

My question is, is this the right approach? If it is, what am I doing wrong and if it's not can someone please point me in the right direction.


try with the following code

public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,
            int targetHeight) {
        Bitmap bitMapImage = null;
        // First, get the dimensions of the image
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        double sampleSize = 0;
        // Only scale if we need to
        // (16384 buffer for img processing)
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
                .abs(options.outWidth - targetWidth);

        if (options.outHeight * options.outWidth * 2 >= 1638) {
            // Load, scaling to smallest power of 2 that'll get it <= desired
            // dimensions
            sampleSize = scaleByHeight ? options.outHeight / targetHeight
                    : options.outWidth / targetWidth;
            sampleSize = (int) Math.pow(2d,
                    Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }

        // Do the actual decoding
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = BitmapFactory.decodeFile(filePath, options);

                break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {

                }
            }
        }

        return bitMapImage;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜