png 文件压缩为 jpeg 时变成全黑。是因为PNG是无损的吗?
我有一段代码,可以以一定的质量压缩jpg图像,但是当图像是png类型时,它们都变成黑色。知道为什么以及如何解决它吗?这是我的代码。
public void compressImage(String filename, ServletContext servletContext) {
//You first need to enumerate the image writers that are available to jpg
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
//Then, choose the first image writer available
ImageWriter writer = (ImageWriter) iter.next();
//instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
//Set the compression quality
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.5f);
try {
BufferedImage img = ImageIO.read(new File(filename));
String destPath = "/Users/KingdomHeart/resources/scholar/compress/compress.jpg";
File file = new File(destPath);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, iwp);
writer.dispose();
}catch(IOException e){
}
}
I have a piece of code that compress an jpg image with a certain quality, but when the image is png type, they all turn black. Any idea why and how to fix it? here is my code.
public void compressImage(String filename, ServletContext servletContext) {
//You first need to enumerate the image writers that are available to jpg
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
//Then, choose the first image writer available
ImageWriter writer = (ImageWriter) iter.next();
//instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
//Set the compression quality
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.5f);
try {
BufferedImage img = ImageIO.read(new File(filename));
String destPath = "/Users/KingdomHeart/resources/scholar/compress/compress.jpg";
File file = new File(destPath);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, iwp);
writer.dispose();
}catch(IOException e){
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能有您正在寻找的答案:转换透明 gif / png使用 java 转换为 jpeg
问题可能是您正在使用具有一定透明度的 PNG。
This might have the answers you're looking for: Converting transparent gif / png to jpeg using java
The issue is likely that you're working with a PNG that has some transparency in it.