使用BufferedImage将图像质量降低(变成偏红)为JPEG

时间:2017-04-20 09:23:38

标签: java image image-processing jpeg

我正在制作一个程序,我从图像中提取像素数组,取出ARGB值。并再次写回来制作另一张图片。

        BufferedImage imagebuffer = ImageIO.read(new File("C:\\Users\\Ramandeep\\Downloads\\w3.jpg"));
        iw = imagebuffer.getWidth();
        ih = imagebuffer.getHeight();

        pixels = new int[iw * ih];
        PixelGrabber pg = new PixelGrabber(imagebuffer, 0, 0, iw, ih, pixels, 0, iw);
        pg.grabPixels();  

      BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      image.setRGB(0, 0, width, height, pixels, 0, width);


        ImageIO.write(image, "jpg", new File("C:\\Users\\Ramandeep\\Desktop\\out.jpg"));
        ImageIO.write(image, "gif", new File("C:\\Users\\Ramandeep\\Desktop\\out.gif"));
        ImageIO.write(image, "png", new File("C:\\Users\\Ramandeep\\Desktop\\out.png"));

现在png和gif的输出图像看起来很好,但输出jpg图像显得偏红。

这是原始图片 enter image description here 这是输出jpg图像  enter image description here

知道可能导致这种情况的原因是什么?任何向正确方向的推动都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

我不知道这是否适合你,但我总是逐个像素地做。 所以:

BufferedImage imagebuffer = ImageIO.read(new File("C:\\Users\\Ramandeep\\Downloads\\w3.jpg"));
iw = imagebuffer.getWidth();
ih = imagebuffer.getHeight();
BufferedImage image = new BufferedImage(iw,ih,BufferedImage.TYPE_INT_ARGB);
for (int x=0; x < iw; x++) {
     for (int y=0; y < ih; y++) {
          image.setRGB(x,y,imagebuffer.getRGB(x,y));
     }
}
ImageIO.write(image, "jpg", new File("C:\\Users\\Ramandeep\\Desktop\\out.jpg"));
ImageIO.write(image, "gif", new File("C:\\Users\\Ramandeep\\Desktop\\out.gif"));
ImageIO.write(image, "png", new File("C:\\Users\\Ramandeep\\Desktop\\out.png"));

这种方式有类似的行数,所以我想你可以尝试一下。

如果你想插入文本,id ìmport java.awt.*;,包括Graphics和Graphics2D以及Font,那么:

Font font=new Font("Sans,0,20); //Name, type(none, bold, italic), size
Graphics2D imagegraphics=imagebuffer.createGraphics();
imagegraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //enable antialiasing
imagegraphics.setFont(font);
imagegraphics.setColor(Color.BLACK);
String yourtext="Fighter";
int h=imagegraphics.getFontMetrics().getHeight();
int w=imagegraphics.getFontMetrics().stringWidth(yourtext);
imagegraphics.drawString(yourtext,5,h); //Draw text upper left corner, note that y-value is the bottom line of the string

编辑:

这是Alpha值。修正:

BufferedImage image = new
BufferedImage(iw,ih,BufferedImage.TYPE_INT_RGB); //RGB, jpeg hasnt got alpha, ints have been converted as if they contain red first, but its alpha(the first bytes, these ints are interpreted bitwise i think) (argb), so it became more red.