如何使用最少的内存使用率裁剪位图?

时间:2012-03-08 14:17:23

标签: android bitmap crop out-of-memory

在我的应用程序中,我正在从网络上加载大量图像。到目前为止工作正常:

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

    ...
}

但事实上,在应用程序过程中仅使用图像的提取物会很好。所以我试过这样的事情:

@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;

    ...
}

但是我的应用程序在加载几十个图像(OutOfMemoryException)后不断崩溃。所以(我猜)我有两个机会摆脱30个像素的高度(它实际上是一个信用信息,但不要担心,我不偷,如果我隐藏它就没关系):

  • Crop&使用较少的内存使用量保存图像,或
  • 操纵ImageView以隐藏图像的底部(高度可能因缩放而有所不同)

但是我需要一些关于这些技术的建议。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

    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;
    }

这尚未经过测试,但这样的事情可能会成功。

答案 1 :(得分:0)

使用位图保存内存的常用方法是将图像解码为预先缩放的空间以满足您的需要。这是一个(可能太)简单的example。 (更好的方法是将比例因子限制为2的幂。)

答案 2 :(得分:-1)

Hai请使用此代码

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);

在这个例子中,图像“ss”将缩放或调整它帮助你的东西

相关问题