gpt4 book ai didi

java - 压缩java中的二维图形写入图像大小

转载 作者:行者123 更新时间:2023-12-01 19:48:19 25 4
gpt4 key购买 nike

我有一个图像,并在java中使用java.awt.Graphics2D我在图像上写了一个文本。直到这里一切都正常。当我尝试在java中使用ImageWriteParam在java中压缩这个图像时,图片被夸大了。下面是我用来压缩图像大小的代码。不过,此代码对于普通图像来说效果很好。

    File input = new File("Input Image File");
BufferedImage image = ImageIO.read(input);

File compressedImageFile = new File("Compressed image file location");
OutputStream os = new FileOutputStream(compressedImageFile);

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

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

ImageWriteParam param = writer.getDefaultWriteParam();

param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(1.0f); // Change the quality value you prefer
try {
writer.write(null, new IIOImage(image, null, null), param);
System.out.println(writer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

os.close();
ios.close();
writer.dispose();

感谢任何帮助。谢谢!

最佳答案

您使用默认的ImageWriterParams,使用writer.getDefaultWriteParam()。但正如 API of the ImageWriter 中提到的它在这里说:

[...] The default implementation constructs and returns a new ImageWriteParam object that does not allow tiling, progressive encoding, or compression...

还有关于如何处理该问题的提示,

individual plug-ins may return an instance of ImageWriteParam with additional optional features enabled, or they may return an instance of a plug-in specific subclass of ImageWriteParam.

关于java - 压缩java中的二维图形写入图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59104438/

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