gpt4 book ai didi

Java 为什么我生成的图像总是翻转和旋转?

转载 作者:行者123 更新时间:2023-12-02 04:12:49 24 4
gpt4 key购买 nike

我正在尝试访问每个像素,对其进行操作,然后将其保存回系统。但生成的图像总是翻转和旋转,这是为什么呢?这是我的输入代码:

 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();
}

您可以在下面看到输入和输出图像 OutputImage

Input Image

最佳答案

你很困惑(或者至少我很困惑),因为你得到的数组是高乘宽(不是宽度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

关于Java 为什么我生成的图像总是翻转和旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33622527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com