Tha*_*ham 6 java compression jpeg image-compression javax.imageio
当我尝试压缩jpg图像时,大多数情况下它完美地工作,但是一些jpg图像在压缩后变为绿色.这是我的代码
public void compressImage(String filename, String fileExtension) {
BufferedImage img = null;
try {
File file = new File(filename);
img = ImageIO.read(file);
if (fileExtension.toLowerCase().equals(".png") || fileExtension.toLowerCase().equals(".gif")) {
//Since there might be transparent pixel, if I dont do this,
//the image will be all black.
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
int rgb = img.getRGB(x, y);
int alpha = (rgb >> 24) & 0xff;
if (alpha != 255) {
img.setRGB(x, y, -1); //set white
}
}
}
}
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.8f);
//delete the file. If I dont the file size will stay the same
file.delete();
ImageOutputStream output = ImageIO.createImageOutputStream(new File(filename));
writer.setOutput(output);
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, iwp);
writer.dispose();
} catch (IOException ioe) {
logger.log(Level.SEVERE, ioe.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)

根据经验,我知道绿色是新格式化的 YUV 内存(特别是 YV12)的颜色。所以我的猜测是某个步骤失败了,你得到了亮度信息,但色度被破坏了。在我看来,它在到达 Cr 飞机之前就失败了。
无论如何,祝你好运,这很难。不过你的代码看起来很奇怪——顶部奇怪的 png 特定代码是怎么回事?AFAIK,如果您使用 .NET,您几乎可以将任何注册的图像格式视为没有任何有趣工作的图像。
| 归档时间: |
|
| 查看次数: |
1437 次 |
| 最近记录: |