如果我将PNG图像打开为BufferedImage,是否可以减少PNG图像中的调色板以减少颜色(每像素位数/颜色深度较少)?
例如,如果您查看维基百科中的Colour depth,我想在PNG图像中使用16种颜色(右侧第3张图像)。
如果Java 2D无法实现,那么是否有一个可以让我有效地执行此操作的库?
答案 0 :(得分:8)
我认为Martijn Courteaux是对的:
以下是示例实现:
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
}
}
答案 1 :(得分:3)
使用下方调色板创建一个新的BufferedImage,并使用createGraphic()
获取Graphics2D
个对象。在图形上绘制原始图像。 dispose()
图形和你在这里。
BufferedImage img = new BufferedImage(orig.getWidth(), orig.getHeight(),
BufferedImage.TYPE_USHORT_555_RGB);