我试图访问每个像素,操纵它,然后将它保存回系统中。但是最终的图像总是被翻转和旋转,为什么会这样呢?这是我的输入代码:
BufferedImage input_image=ImageIO.read(new File("F:\\sophie4.png"));
int result[][] = convertTo2DWithoutUsingGetRGB(input_image);
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;
}这是可行的,我得到像素,但即使没有处理像素,如果我输出图像,它总是翻转。这是我的输出代码:
BufferedImage image = new BufferedImage(result.length, result[0].length, BufferedImage.TYPE_INT_RGB);
for (int row = 0; row < result.length; row ++) {
for (int col = 0; col < result[row].length; col++) {
image.setRGB(row, col, result[row][col]);
}
}
File ImageFile = new File("path");
try {
ImageIO.write(image, "png", ImageFile);
} catch (IOException e) {
e.printStackTrace();
}您可以看到下面的输入和输出图像


发布于 2015-11-10 04:24:47
您正在感到困惑(或者至少我是这样),因为您的数组是按宽度计算的高度(不是对我来说更有意义的宽度x高度),所以,而不是.
BufferedImage image = new BufferedImage(result.length, result[0].length, BufferedImage.TYPE_INT_RGB);应该是..。
BufferedImage image = new BufferedImage(result[0].length, result.length, BufferedImage.TYPE_INT_RGB);和
image.setRGB(row, col, result[row][col]);应该是
image.setRGB(col, row, result[row][col]); // See why that's consfusinghttps://stackoverflow.com/questions/33622527
复制相似问题