【问题标题】:Bitmap compress doesn't changing bitmap byte size位图压缩不会改变位图字节大小
【发布时间】:2017-02-28 19:52:34
【问题描述】:

我正在尝试使用压缩方法来减小位图大小。

这是我的代码:

public Bitmap compressImage(Bitmap image) {
        Bitmap immagex = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Log.i("before compress", immagex.getByteCount()+"");

        boolean compress = immagex.compress(Bitmap.CompressFormat.JPEG, 10, baos);

        if(compress)
            Log.i("after compress", immagex.getByteCount()+"");
        else
            Log.i("bad compress", "bad compress");

        return immagex;
    }

当我检查我的日志时,我得到:

11-28 11:10:38.252: I/before compress(2429): 374544
11-28 11:10:38.262: I/after compress(2429): 374544

为什么压缩不起作用?

更新:

我试过这段代码:

public Bitmap compressImage(Bitmap image) {
        Bitmap immagex = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Log.i("before compress", immagex.getByteCount()+"");

        boolean compress = immagex.compress(Bitmap.CompressFormat.JPEG, 10, baos);

        Log.i("after compress 2", decodeSampledBitmapFromByte(image.getWidth(), image.getHeight(), baos.toByteArray()).getByteCount()+"");

        return immagex;
    }

还是一样的字节数

11-28 11:33:04.335: I/before compress(3472): 374544
11-28 11:33:04.395: I/after compress 2(3472): 374544

【问题讨论】:

  • 这不是我的问题。我不想缩放我的位图只是为了通过改变是 quilaty 来减少内存中的大小。
  • 找到解决这个问题的方法了吗?我在这里面临同样的问题。
  • 我面临同样的问题。实际上我的字节数组随着压缩参数的降低而增加

标签: android bitmap


【解决方案1】:

以下是减小位图大小并将其转换为base64的代码,

    Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] byteArray = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

    Log.e("Base 64 String", imageEncoded);

【讨论】:

  • 感谢您的评论,但我已经尝试过其他不使用更改大小的解决方案...
  • 这对我也不起作用。这是 Android 错误吗?
【解决方案2】:

使用 Bitmap.compress() 您只需指定压缩算法,并且压缩操作需要相当长的时间。如果您需要调整大小以减少图像的内存分配,您确实需要使用 Bitmap.Options 对图像进行缩放,首先计算位图边界,然后将其解码为您指定的大小。

我在 StackOverflow 上找到的最好的示例就是这个。 Strange out of memory issue while loading an image to a Bitmap object

【讨论】:

  • 我不想缩放位图只是为了降低质量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2015-08-04
相关资源
最近更新 更多