2 Steps to read data of image into byte array in Android



Sometimes, we need read an image in assets directory to display in android, at this situation, we may need read data of image into a byte array so that we can use it in other place of our program. To read data of an image into a byte data is very simple, we can do like this:

Step 1: Put an image into assets directory in Android project

Before we start to coding, we should place an image into assets directory in android project, it may like this:

image in assets directory

Step 2: Read data of image into a byte array

After we have place an image into assets directory, we can read its data into a byte array, this sample code realize read data of an image  in assets directory into a byte array, then display it on imageview.

show image from assets in android

Smaple code like this:


public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 ImageView imageView = (ImageView) this.findViewById(R.id.image_id);
 //read an image in assets
 byte[] data = readImageFromAssets("logo.png");
 Bitmap bitmap = null;
 try {
 bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
 } catch(Exception e) {
 if(null != bitmap) {
 bitmap.recycle();
 bitmap = null;
 }
 }
 if(bitmap != null) {
 Drawable drawable =new BitmapDrawable(bitmap);
 imageView.setBackgroundDrawable(drawable);
 }
 }
 /** read a image into byte array from assets */
 private byte[] readImageFromAssets(String imageName) {
 InputStream is = null;
 ByteArrayOutputStream out = null;
 try {
 is = getBaseContext().getAssets().open(imageName);
 out = new ByteArrayOutputStream(1024);
 byte[] temp = new byte[1024];
 int size = 0;
 while ((size = is.read(temp)) != -1) {
 out.write(temp, 0, size);
 }
 byte[] content = out.toByteArray();

 if(is != null) {
 is.close();
 }
 if(out != null) {
 out.close();
 }
 return content;
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } finally {

 }
 return null;

 }