我试图从64 x 48
位图中获取像素rgb值.我得到了一些价值,但远不及3072 (= 64 x 48)
我期待的价值.我也得到:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds! at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:301) at java.awt.image.BufferedImage.getRGB(BufferedImage.java:871) at imagetesting.Main.getPixelData(Main.java:45) at imagetesting.Main.main(Main.java:27)
我找不到越界错误...
这是代码:
package imagetesting; import java.io.IOException; import javax.imageio.ImageIO; import java.io.File; import java.awt.image.BufferedImage; public class Main { public static final String IMG = "matty.jpg"; public static void main(String[] args) { BufferedImage img; try { img = ImageIO.read(new File(IMG)); int[][] pixelData = new int[img.getHeight() * img.getWidth()][3]; int[] rgb; int counter = 0; for(int i = 0; i < img.getHeight(); i++){ for(int j = 0; j < img.getWidth(); j++){ rgb = getPixelData(img, i, j); for(int k = 0; k < rgb.length; k++){ pixelData[counter][k] = rgb[k]; } counter++; } } } catch (IOException e) { e.printStackTrace(); } } private static int[] getPixelData(BufferedImage img, int x, int y) { int argb = img.getRGB(x, y); int rgb[] = new int[] { (argb >> 16) & 0xff, //red (argb >> 8) & 0xff, //green (argb ) & 0xff //blue }; System.out.println("rgb: " + rgb[0] + " " + rgb[1] + " " + rgb[2]); return rgb; } }
John Kugelma.. 12
这个:
for(int i = 0; i < img.getHeight(); i++){ for(int j = 0; j < img.getWidth(); j++){ rgb = getPixelData(img, i, j);
与此不匹配:
private static int[] getPixelData(BufferedImage img, int x, int y) {
您已i
计算行和j
列,即i
包含y值并j
包含x值.那是倒退.
这个:
for(int i = 0; i < img.getHeight(); i++){ for(int j = 0; j < img.getWidth(); j++){ rgb = getPixelData(img, i, j);
与此不匹配:
private static int[] getPixelData(BufferedImage img, int x, int y) {
您已i
计算行和j
列,即i
包含y值并j
包含x值.那是倒退.
我一直在寻找同样的能力.不想枚举整个图像,所以我做了一些搜索并使用了PixelGrabber.
Image img = Toolkit.getDefaultToolkit().createImage(filename); PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, false); pg.grabPixels(); // Throws InterruptedException width = pg.getWidth(); height = pg.getHeight(); int[] pixels = (int[])pg.getPixels();
您可以int[]
直接使用此处,像素采用ColorModel指定的格式pg.getColorModel()
,或者您可以将false更改为true并强制它为RGB8-in-int.
我已经发现,Raster
和类也可以这样做,并且已经添加了一些有用的类javax.imageio.*
.
BufferedImage img = ImageIO.read(new File(filename)); // Throws IOException int[] pixels = img.getRGB(0,0, img.getWidth(), img.getHeight, null, 0, img.getWidth()); // also available through the BufferedImage's Raster, in multiple formats. Raster r = img.getData(); int[] pixels = r.getPixels(0,0,r.getWidth(), r.getHeight(), (int[])null);
还有几种getPixels(...)
方法Raster
.
这也有效:
BufferedImage img = ImageIO.read(file); int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();