Byte array of image into imageview

Manoj Kumar picture Manoj Kumar · Dec 13, 2012 · Viewed 70k times · Source

I've searched a bit but can't get a clear glimpse of it. How can I set a byte array of an Image into an ImageView? I tried with this but it didn't work.

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

Answer

Dipak Keshariya picture Dipak Keshariya · Dec 13, 2012

This is how you can convert a Bitmap to a ByteArray and a ByteArray to a Bitmap:


Convert Bitmap to ByteArray:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Convert ByteArray to Bitmap:

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false));