我试图访问每个像素,操纵它然后将其保存回系统。但是生成的图像总是翻转和旋转,为什么会这样? 这是我输入的代码:
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();
}
答案 0 :(得分:2)
你感到困惑(或者至少我是),因为你的结果是高度和宽度(不是宽度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 consfusing