Reputation: 23
There is a very simple .jpg image which i want to convert to a matrix. But using getRGB(i,j) for pointing to pixel is giving runtime exception of ArrayIndexOutOfBounds. Is there any restrictions for the size of the image for following code? And it is just displaying the first color code it gets for throughout the image.
BufferedImage img=ImageIO.read(new File("stars.jpg"));
int pix[][]= new int[img.getHeight()][img.getWidth()];
and then I applied a nested for loop and used
pix[i][j]= img.getRGB(i,j);
Upvotes: 2
Views: 5561
Reputation: 4076
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtil {
public static Color[][] loadPixelsFromFile(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
Color[][] colors = new Color[image.getWidth()][image.getHeight()];
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
colors[x][y] = new Color(image.getRGB(x, y));
}
}
return colors;
}
public static void main(String[] args) throws IOException {
Color[][] colors = loadPixelsFromFile(new File("stars.jpg"));
System.out.println("Color[0][0] = " + colors[0][0]);
}
}
Upvotes: 1
Reputation: 4076
You probably swapped width and height.
Try replacing
int pix[][]= new int[img.getHeight()][img.getWidth()];
with
int pix[][]= new int[img.getWidth()][img.getHeight()]; // <--- width first
Upvotes: 0
Reputation: 1934
This function does exactly what you mentioned and it works fine for me. I believe you may have done something wrong in your nested for loop.
public int[][] getMatrixOfImage(BufferedImage bufferedImage) {
int width = bufferedImage.getWidth(null);
int height = bufferedImage.getHeight(null);
int[][] pixels = new int[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
pixels[i][j] = bufferedImage.getRGB(i, j);
}
}
return pixels;
}
Upvotes: 1