How to crop a Bitmap with a minimum usage of memory?

点点圈 提交于 2019-12-11 12:24:49

问题


In my app I'm loading plenty of images from the web. That's working fine so far:

@Override
public void onSuccess( byte[] response )
{
    Bitmap image = BitmapFactory.decodeByteArray( response, 0, response.length, options );

    ...
}

But in fact it would be nice to use only an extract of the image during the application process. So I tried something like this:

@Override
public void onSuccess( byte[] response )
{
    Bitmap source = BitmapFactory.decodeByteArray( response, 0, response.length, options );
    Bitmap image = Bitmap.createBitmap( source, 0, 0, source.getWidth(), source.getHeight() - 30 );
    source.recycle();
    source = null;

    ...
}

But my app keeps crashing after loading a few dozens of images (OutOfMemoryException). So (I guess) I have two opportunities to get rid off the 30 pixels of height (it's actually a credit information, but don't worry, I'm not stealing, it's okay if I hide it):

  • Crop & save the image with less memory usage, or
  • Manipulate the ImageView to hide the bottom of the image (height may vary due to scaling)

But I need some advice for these techniques.


回答1:


Try something like this:

    private Bitmap trimImage(Bitmap source)
    {
        int trimY = 20; //Whatever you want to cut off the top
        Bitmap bmOverlay = Bitmap.createBitmap(source.getWidth(), source.getHeight(), source.getConfig());
        Canvas c = new Canvas(bmOverlay);

        //Source and destination Rects based on sprite animation.
        Rect srcRect = new Rect(0, trimY, source.getWidth(), source.getHeight()); 
        Rect dstRect = new Rect(0, 0, source.getWidth(), source.getHeight());
        c.drawBitmap(manual1, srcRect, dstRect, null);

        return bmOverlay;
    }

This hasn't been tested, but something like this might do the trick.




回答2:


A common approach to saving memory with bitmaps is to decode the image into a space which is pre-scaled to suit your purpose. Here is a (probably too) simple example. (A better approach would restrict the scale factor to powers of 2.)




回答3:


Hai please use this code

ImageView image = (ImageView) findViewById(R.id.sd);
    Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.ss);

    Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, 180, 220, true);
    image.setImageBitmap(bMapScaled);

in this example the image "ss" will Scale or resized thing it helped you



来源:https://stackoverflow.com/questions/9619032/how-to-crop-a-bitmap-with-a-minimum-usage-of-memory

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