PNG - ¿Es posible reducir la paleta usando Java 2D?
-
27-10-2019 - |
Pregunta
Si tengo una imagen PNG abierta como una imagen de buffered, ¿es posible reducir la paleta en la imagen PNG para que haya menos color (menos bits por píxel / profundidad de color)?
Por ejemplo, si miras Profundidad de color En Wikipedia, me gustaría usar 16 colores en mi imagen PNG (tercera imagen en el lado derecho).
Si no es posible con Java 2D, ¿hay una biblioteca que me permita hacerlo de manera efectiva?
Solución
Creo que Martijn Courteaux tenía razón:
Aquí hay una implementación de ejemplo:
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
}
}
Otros consejos
Cree una nueva BufferedImage con la paleta inferior y use createGraphic()
para adquirir un Graphics2D
objeto. Dibuja la imagen original en los gráficos. dispose()
los gráficos y aquí estás.
BufferedImage img = new BufferedImage(orig.getWidth(), orig.getHeight(),
BufferedImage.TYPE_USHORT_555_RGB);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow