PNG - Is it possible to reduce the palette using Java 2D?

可紊 提交于 2019-12-03 03:29:11

I think Martijn Courteaux was right:

Here is example implementation:

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImagingTest2 {
    public static void main(String[] args) throws IOException {
        BufferedImage src = ImageIO.read(new File("in.png")); // 71 kb

        // here goes custom palette
        IndexColorModel cm = new IndexColorModel(
                3, // 3 bits can store up to 8 colors
                6, // here I use only 6
                //          RED  GREEN1 GREEN2  BLUE  WHITE BLACK              
                new byte[]{-100,     0,     0,    0,    -1,     0},
                new byte[]{   0,  -100,    60,    0,    -1,     0},
                new byte[]{   0,     0,     0, -100,    -1,     0});

        // draw source image on new one, with custom palette
        BufferedImage img = new BufferedImage(
                src.getWidth(), src.getHeight(), // match source
                BufferedImage.TYPE_BYTE_INDEXED, // required to work
                cm); // custom color model (i.e. palette)
        Graphics2D g2 = img.createGraphics();
        g2.drawImage(src, 0, 0, null);
        g2.dispose();

        // output
        ImageIO.write(img, "png", new File("out.png"));   // 2,5 kb
    } 
}

Create a new BufferedImage with the lower palette and use createGraphic() to acquire a Graphics2D object. Draw the original image on the graphics. dispose() the graphics and here you are.

BufferedImage img = new BufferedImage(orig.getWidth(), orig.getHeight(),
                                      BufferedImage.TYPE_USHORT_555_RGB);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!