Marcio
Marcio

Reputation: 617

Convert a BufferedImage into a 2D array

I have a BufferedImage which represents a 2048X2048 pixels tiff image. I wish to retrieve such array (int [2048][2048] from the BufferedImage. How should I proceed?

Upvotes: 2

Views: 12594

Answers (2)

Charlie
Charlie

Reputation: 4895

This method will return the red, green and blue values directly for each pixel, and if there is an alpha channel it will add the alpha value. Using this method is harder in terms of calculating indices, but is much faster than the first approach.

 private static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {

  final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
  final int width = image.getWidth();
  final int height = image.getHeight();
  final boolean hasAlphaChannel = image.getAlphaRaster() != null;

  int[][] result = new int[height][width];
  if (hasAlphaChannel) {
     final int pixelLength = 4;
     for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
        int argb = 0;
        argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
        argb += ((int) pixels[pixel + 1] & 0xff); // blue
        argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
        argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
        result[row][col] = argb;
        col++;
        if (col == width) {
           col = 0;
           row++;
        }
     }
  } else {
     final int pixelLength = 3;
     for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
        int argb = 0;
        argb += -16777216; // 255 alpha
        argb += ((int) pixels[pixel] & 0xff); // blue
        argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
        argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
        result[row][col] = argb;
        col++;
        if (col == width) {
           col = 0;
           row++;
        }
     }
  }

  return result;
 }

Upvotes: 1

a_schimpf
a_schimpf

Reputation: 765

arr = new int[2048][2048];

for(int i = 0; i < 2048; i++)
    for(int j = 0; j < 2048; j++)
        arr[i][j] = image.getRGB(i, j);

Since you can get the RGB value of each pixel from the image data structure itself, it might be a benefit to NOT copy everything over to a 2d array.

Upvotes: 2

Related Questions