Handling large bitmap in android

删除回忆录丶 提交于 2019-12-12 21:18:25

问题


I just want to open native camera app from my app to capture a photo and set it as a background image of my screen then rotate it onclick of button. Photo is rotating n number of times if it is taken with 3MP camera. If i set camera resolution to 5MP or more, app is force closing on click of button 5th time (photo is rotating 4 times) .

Bitmap rotatedBitmap = null; 
int curAngle = 0; 

private Bitmap rotateImageBitmap(Bitmap capturedPhotoBitmap) {       

if(rotatedBitmap != null  ) 
{ 
    rotatedBitmap = null; 
} 

Matrix matrix = new Matrix(); 
curAngle = (curAngle + 90) % 360; 
matrix.postRotate(curAngle); 
rotatedBitmap =  Bitmap.createBitmap(capturedPhotoBitmap, 0, 0,  capturedPhotoBitmap.getWidth(),  capturedPhotoBitmap.getHeight(), matrix, true); 

return rotatedBitmap;         
 } 

This is from Developer Guide ....
1. Mobile devices typically have constrained system resources. Android devices can have as little as 16MB of memory available to a single application.

2. Bitmaps take up a lot of memory, especially for rich images like photographs. For example, the camera on the Galaxy Nexus takes photos up to 2592x1936 pixels (5 megapixels). If the bitmap configuration used is ARGB_8888 (the default from the Android 2.3 onward) then loading this image into memory takes about 19MB of memory (2592*1936*4 bytes), immediately exhausting the per-app limit on some devices.

Most phones nowadays have cameras 8mp or higher. so pictures will be large. How can i rotate my photo 'n' number of times without bothering of camera resolution. Do i need to compress it ? What is the best way? Please help me.


回答1:


Rather than having the image on the heap in RAM, I would load (read: buffer) the image onto disk in your app's cache directory. http://developer.android.com/reference/android/content/Context.html#getCacheDir()

After the image is on disk, I would then inflate it into memory using a sample size to reduce memory consumption.

See http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize and http://developer.android.com/reference/android/graphics/BitmapFactory.html

The sample size you pick is relative to the size of the bitmap (in pixels) and the size of the view you are loading the image to (in pixels).

To find the image's dimensions, use the "inJustDecodeBounds" option in the BitmapFactory.Options object.

Remember that the sample size you choose should be a power of 2. The higher the number is, the more memory you save, but the lower the quality of the image.

Sample size 2 = 1/4 the size. Sample size 4 = 1/16 the size, etc.



来源:https://stackoverflow.com/questions/11183210/handling-large-bitmap-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!