PNG - 是否可以使用Java 2D减少调色板? [英] PNG - Is it possible to reduce the palette using Java 2D?

查看:286
本文介绍了PNG - 是否可以使用Java 2D减少调色板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将PNG图像打开为BufferedImage,是否可以减少PNG图像中的调色板以减少颜色(每像素位数/颜色深度较少)?

If I have a PNG image opened as a BufferedImage, is it possible to reduce the palette in the PNG image so that there is less colour (less bits per pixel / colour depth)?

例如,如果您查看维基百科中的颜色深度,我希望在我的PNG图像中使用16种颜色(右手边的第3张图片)。

For example, if you look at Colour depth in Wikipedia, I would like to use 16 colours in my PNG image (3rd image down the right hand side).

如果使用Java 2D是不可能的,那么是否有一个库允许我有效地这样做了吗?

If it's not possible with Java 2D, is there a library out there that will allow me to do this effectively?

推荐答案

我认为Martijn Courteaux是对的:

I think Martijn Courteaux was right:

以下是示例实现:

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
    } 
}

这篇关于PNG - 是否可以使用Java 2D减少调色板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆