开发者

Memory efficient way to scale an image

I've got an app where the main viewing area is a WebView.

It's a service where a user can also upload a photo. However, with the WebView, and photo uploads, I'm getting some OutOfMemoryErrors.

Usually all it takes is a page loa开发者_运维技巧ded in the WebView, and then simply trying to open an image with something like this:

Bitmap bmp = BitmapFactory.decodeFile(path);

The only reason I need to open the file at all is so that I can scale it down so that it fits in a max width/max height dimensions before uploading it.

I've even tried opening it in a sampled fashion, similar to what's mentioned here:

Strange out of memory issue while loading an image to a Bitmap object

However, with a complex webpage loaded in the WebView, I still get OutOfMemoryError when trying to open the image.

Is there a way to scale it, maybe using another process or something, that's more memory efficient?


I'm glad you asked, I was about to investigate this for my own project.

It looks like BitmapFactory.Options is your friend here, specifically BitmapFactory.Options.inSampleSize enter link description here. You can use BitmapFactory.decodeStream to get the image dimensions without creating a Bitmap.

Googling revealed the com.bristle.javalib.awt ImgUtil classes; these appear to be open source (don't know the license), and are AWT based, so may work on Android. The interesting method is ImgUtil.scalueImageToOutputStreamAsJPEG, which works with InputSteam/OutputStream, so may be memory efficient.

UPDATE

An alternative is to write a JNI wrapper around /system/lib/libjpeg.so, which appears to be standard on Android devices. This library works with scanlines, so can be memory friendly. Another plus is that using JNI should be faster than pure java.

Hope this helps,

Phil Lello


I had a similar problem and found a workable solution using BitmapFactory.Option.inScale. You can find details here: How do I scale a streaming bitmap in-place without reading the whole image first?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜