gpt4 book ai didi

Java:BufferedImage 上的 getHeight() 返回图像宽度,getWidth() 返回图像高度

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:04:39 31 4
gpt4 key购买 nike

我正在用 Java 对图像进行 Jpeg 压缩,然后在存储前调整它们的大小。我将存储高度保持为 480 并根据宽高比计算 height,以便保持原始 height:width 比例相同。

这是我使用的代码

String inputImagePath = "1.JPG";
String outputImagePath = "Test Compression\\" + "1.JPG";

File imageFile = new File(inputImagePath);
File compressedImageFile = new File(outputImagePath);

int height = 640;

System.out.print("Conversion Start!\n");

if (imageFile != null)
{

InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);

float quality = 0.2 f;

BufferedImage image = ImageIO.read(is);

double aspectRatio = (double) image.getWidth() / image.getHeight();

width = (int)(height * aspectRatio);
System.out.println("Original height = " + image.getHeight() + " Original width = " + image.getWidth());
System.out.println(" aspect ratio = " + aspectRatio);
System.out.println("height = " + height + " width = " + width + " aspect ratio = " + aspectRatio);

BufferedImage resizedImage = new BufferedImage(width, height, image.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose();

Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");

if (!writers.hasNext())
throw new IllegalStateException("No writers found");

ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);

ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);

writer.write(null, new IIOImage(resizedImage, null, null), param);
}

System.out.print("Conversion compete!");

这是图像元数据

Here width = 1920, height = 2560

打印内容如下:

Original height = 1920 Original  width = 2560
aspect ratio = 1.3333333333333333

height = 480 width = 640
aspect ratio = 1.3333333333333333

我将代码应用于实际具有 width > height 的其他图像,并且没有旋转问题。此旋转问题仅发生在具有 height > width 的图像上 据我所知,我的代码没有任何问题,我一定是遗漏了与 getHeight() 和 getWidth() 函数相关的内容。请帮帮我

最佳答案

在默认情况下,Java 无法识别的 jpeg 图像中可能存在旋转元数据。

在 jpeg 属性中看起来像:Orientation : rotate 90

您需要第 3 方库来处理它,请参阅 How to rotate JPEG images based on the orientation metadata?

关于Java:BufferedImage 上的 getHeight() 返回图像宽度,getWidth() 返回图像高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866506/

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