Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

android - how to avoid OUtOfMemory problems with create Bitmap

I'm trying to create a bitmap from a view with this code :

public Bitmap getmyBitmap(View v)
{
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
        Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        return b;
}

But I have an Out Of Memory problems. I can fix it by adding this option to the Manifest file android:largeHeap="true" which is not recommended !!

I'm thinking about the recycle of the view ,could be a solution?

this is the printStack:

11-25 15:31:46.556 2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 4096016-byte allocation. 11-25 15:31:46.616
2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 4096016-byte allocation. 11-25 15:31:46.666
2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 4096016-byte allocation. 11-25 15:31:54.016
2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 1879696-byte allocation. 11-25 15:31:54.016
2115-2115/com.myproject.android E/AndroidRuntime﹕ FATAL EXCEPTION: main

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are getting a lot of Bitmaps which overloads your system memory, or if it a single one a think it's an extremely huge one, So, to solve the problem, you have to do two things, first make sure you don't run this method a lot of times for the same Bitmap(as that leads to a lot of Bitmaps stored in your memory and all of them belonging to the same one), second use a custom method to scale your Bitmaps in order to lower it's size and hence it's memory occupation area:

// to scale your Bitmaps
// assign newWidth and newHeight with the corresponding width and height that doesn't make your memory overloads and in the same time doesn't make your image loses it's Features
public static Bitmap scaleBitmap(Bitmap bitmapToScale, float newWidth, float newHeight) {

    if(bitmapToScale == null)
        return null;
    //get the original width and height
    int width = bitmapToScale.getWidth();
    int height = bitmapToScale.getHeight();
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();

    // resize the bit map
    matrix.postScale(newWidth / width, newHeight / height);

    // recreate the new Bitmap and set it back
    return Bitmap.createBitmap(bitmapToScale, 0, 0, bitmapToScale.getWidth(), bitmapToScale.getHeight(), matrix, true);  

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...