位图压缩不会改变位图字节大小

时间:2013-11-28 09:14:13

标签: android bitmap

我正在尝试使用compress方法减少位图大小。

这是我的代码:

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

2 个答案:

答案 0 :(得分:4)

以下是减少位图大小并将其转换为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);

答案 1 :(得分:1)

使用Bitmap.compress(),您只需指定压缩算法,并按压缩操作的方式花费相当多的时间。如果您需要使用大小来减少图像的内存分配,则需要使用Bitmap.Options来缩放图像,首先计算位图边界,然后将其解码为指定的大小。

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

相关问题