creating a java bitmap image from a 3d byte array which contains 3 channel pixel information

Viewed 557

i have a 3 dimensional byte array like this:

byte[][][] data = pyf.callAttr("test", red,green,blue).toJava(byte[][][].class);

here byte[0] which contains two dimensional array having pixel values of red channel

byte[0] is a 480x360 array same as byte[1] and byte[2] which holds green and blue respectively
now i want to create an 360x480 java bitmap image from this 3 dimensional byte array

2 Answers

Some part of the question isn't clear to me like you want to rotate the image or not(the 480x360 to 360x480 part).

So, I am assuming the following things:
(1) you've a proper byte array called data which holds the data as you've described
(2) and you need to create an bitmap from the data
(3) and you can rotate the image if necessary(i.e. this following code doesn't rotate image)

  • the following code is not tested. But it should get you on the right track.
int width = 480;
int height = 360;

int alpha = 1; // change alpha as necessary

Bitmap bmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);

for(int x=0; x<width; x++) {
    for(int y=0; y<height; y++) {
        int red = data[0][x][y];
        int green = data[1][x][y];
        int blue = data[2][x][y];

        int color = Color.argb(alpha, red, green, blue);
        
        bmp.setPixel(x, y, color);
    }
}

Try this as a starting point It won't work on android, as android doesn't support AWT.

public Image createImage(byte[][][] bytes){
   Image image = new BufferedImage(360,480,BufferedImage.TYPE_INT_RGB);
   Graphics g = image.getGraphics();
   for(int x=0;x<480;x++){
      for(int y=0;y<360;y++){
         //Construct color
         Color color=new Color(bytes[0][x][y],bytes[1][x][y],bytes[2][x][y]);
         g.setColor(color);//Set color
         g.fillRect(x,y,1,1);//Fill pixel
      }
   }
   return image;
}

You will have to add error checking and maybe some things like passing the width and height,...

Related