0

如果我将比例设置为大于 1,则图像会拉伸和模糊,否则会出现内存不足异常。如何在不出现内存不足异常的情况下保持图像原始质量。这是我的代码

public Bitmap decodeFile(File f){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //The new size we want to scale to
            final int REQUIRED_SIZE=400;

            //Find the correct scale value. It should be the power of 2.
            int scale=1;
            while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
              scale*=2;
            //scale*=2.5;

            System.gc();
            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
4

2 回答 2

0

像这样改变你的功能

    public Bitmap decodeFile(File f){
    try {
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //The new size we want to scale to
        final int REQUIRED_SIZE=100;

        //Find the correct scale value. It should be the power of 2.
        int scale=1;
        while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
          scale*=2;
        //scale*=2.5;

        System.gc();
        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

现在从你的创建如果你想扩展它然后只需使用

   Bitmap.createScaleBitmap(bitmap src,desired height,desired width,false);

将其存储在一个新的位图中,例如

          Bitmap mynewbitmap =  Bitmap.createScaleBitmap(bitmap src,desired height,desired width,false);

然后在 ImageView.Like 中设置图像

             ImageView.setImageBitmap(mynewbitmap);

注意:-记住一件事 Bitmap DecodeFile 函数是为了从内存中获取文件而创建的,以便我们可以加载图像。如果你不使用它并且直接想要缩放你的位图,那么你会得到 OutOfMemory 错误。所以,算法应该像

第 1 步:- 首先使用解码文件函数解码文件第 2 步:- 使用所需大小 = 100 足够此第 3 步:- 现在使用 CreateScaleBitmap 函数根据您的选择对其进行缩放第 4 步:- 将其设置到您的 ImageView

干杯!!

于 2013-09-08T14:29:27.187 回答
0

这是一个顽固的人..您不能确定OOM是否即将到来,因为编写代码只是因为它是累积的堆内存,超出了分配的内存。

我建议您需要使用 Eclipse MAT 工具来检查您在代码中分配内存(添加位图)的位置。

对于您使用位图的每个地方,不要忘记编写 Bitmap.recycle() ,因为这将帮助您垃圾收集未使用的位图,为您的应用程序提供更多内存用于新的位图。

于 2013-09-08T14:31:42.653 回答