Java – How to convert int array to byte array

How to convert int array to byte array… here is a solution to the problem.

How to convert int array to byte array

int w = width ;
int h =height  ;

Log.i("SopCast", "w:"+w+"-----h:"+h);

int b[]=new int[(int) (w*h)];
int bt[]=new int[(int) (w*h)];
IntBuffer buffer=IntBuffer.wrap(b);
buffer.position(0);
GLES20.glReadPixels(0, 0, w, h,GLES20.GL_RGBA,GLES20.GL_UNSIGNED_BYTE, buffer);
for(int i=0; i<h; i++)
{
      remember, that OpenGL bitmap is incompatible with Android bitmap
      and so, some correction need.
      for(int j=0; j<w; j++)
      {
          int pix=b[i*w+j];
          int pb=(pix>>16)&0xff;
          int pr=(pix<<16)&0x00ff0000;
          pix1=(pix&0xff00ff00) | pr | pb;
          bt[(h-i-1)*w+j]=pix1;
          }
      }
      Bitmap inBitmap = null ;
     if (inBitmap == null || !inBitmap.isMutable()
                    || inBitmap.getWidth() != w || inBitmap.getHeight() != h) {
                inBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            }
            Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            inBitmap.copyPixelsFromBuffer(buffer);
            return inBitmap ;
             return Bitmap.createBitmap(bt, w, h, Bitmap.Config.ARGB_8888);
            inBitmap = Bitmap.createBitmap(bt, w, h, Bitmap.Config.ARGB_8888);

I

got a bitmap with the above code from which I want to get the raw bytes

          IntBuffer buffer=IntBuffer.wrap(b);
          int[] = buffer.array();

How to convert int[] to byte[].

or change the code

                int b[]=new int[(int) (w*h)];
                int bt[]=new int[(int) (w*h)];
                IntBuffer buffer=IntBuffer.wrap(b);

to bytes[].

Can you do me some favors?

Solution

Try this

byte[] ba= new byte[bt.length * 4];

for(int i = 0, k = 0; i < bt.length; i++) {
     int temp= bt[i];
       for(int j = 0; j < 4; j++, k++) {
         ba[k] = (byte)((temp>> (8 * j)) & 0xFF);
     }
}  

Related Problems and Solutions