convert to and from uncompressed bitmap to byte array

故事扮演 提交于 2019-12-13 07:27:05

问题


I am trying to implement two methods.

One that takes an ImageView as input and outputs uncompressed byte array.

The second takes byte array input and converts to a bitmap.

These are the two methods I use however bytesToImage() fails to produce a valid bitmap representation of the output of imageToBytes:

    private static byte[] imageToBytes(ImageView iv) {


        byte[] imageInByte = null;
        Bitmap originalImage;

        BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();

        originalImage = drawable.getBitmap();

        int numOfbytes = originalImage.getByteCount();

        ByteBuffer buffer = ByteBuffer.allocate(numOfbytes);
        originalImage.copyPixelsToBuffer(buffer);
        imageInByte = buffer.array();

        return imageInByte;
}



 private static Bitmap bytesToImage(byte data[]) {


        ByteBuffer byte_buffer = ByteBuffer.wrap(data);

        byte_buffer.rewind();

        Bitmap bmp = Bitmap.createBitmap(60, 60, Bitmap.Config.ARGB_8888);
        bmp.copyPixelsFromBuffer(byte_buffer);

        return bmp;

}

These methods are then called in the following way:

ImageView iv = (ImageView) findViewById(R.id.imageViewInput);
iv.setImageResource(R.drawable.panda);


imageInBytes = imageToBytes(iv);

Bitmap bmp = bytesToImage(imageInBytes);

ImageView image = (ImageView) findViewById(R.id.imageViewOutput);

image.setImageBitmap(bmp);

However the imageViewOutput just displays an empty whitebox.

The image panda is a .bmp image


回答1:


Try this on your imageToBytes method

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

And on your bytesToImage

BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);



回答2:


So the problem is with the bitmap in bytesToImage being incorrectly configured.

This requires the original bitmap to be passed in directly.

Here is the updated bytesToImage method which gives correct answer.

private static Bitmap bytesToImage(byte data[], Bitmap originalImage) {

    Bitmap newBmp;
    newBmp = Bitmap.createBitmap(originalImage.getWidth(), originalImage.getHeight(), originalImage.getConfig());


    ByteBuffer buffer1 = ByteBuffer.wrap(data);

    buffer1.rewind();
    newBmp.copyPixelsFromBuffer(buffer1);

    byte[] imageInByte = null;



    ByteBuffer byte_buffer = ByteBuffer.wrap(data);



    byte_buffer.rewind();



    newBmp.copyPixelsFromBuffer(byte_buffer);


    return newBmp;
}


来源:https://stackoverflow.com/questions/35086901/convert-to-and-from-uncompressed-bitmap-to-byte-array

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