Skip to content

Instantly share code, notes, and snippets.

@lmiguelmh
Created November 18, 2016 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmiguelmh/0f90bf1e5305b84f28c9d358ddecd3c3 to your computer and use it in GitHub Desktop.
Save lmiguelmh/0f90bf1e5305b84f28c9d358ddecd3c3 to your computer and use it in GitHub Desktop.
Color equalization
// color equalization fuuu
int colors = 16;
byte[] r = new byte[colors];
byte[] g = new byte[colors];
byte[] b = new byte[colors];
for (int i = 0; i < colors; i++) {
r[i] = (byte) (i*256/colors & 0xFF);
g[i] = (byte) (i*256/colors & 0xFF);
b[i] = (byte) (i*256/colors & 0xFF);
}
public static byte[] toPng(Image imagen, int newHeight){
BufferedImage bufferedImage = (BufferedImage) imagen;
float quality = 0.9f;
int newWidth = obtenerAnchoProporcional(bufferedImage, newHeight);
// color equalization fuuu
int colors = 16;
byte[] r = new byte[colors];
byte[] g = new byte[colors];
byte[] b = new byte[colors];
for (int i = 0; i < colors; i++) {
r[i] = (byte) (i*256/colors & 0xFF);
g[i] = (byte) (i*256/colors & 0xFF);
b[i] = (byte) (i*256/colors & 0xFF);
}
IndexColorModel cm = new IndexColorModel(4, colors, r, g, b);
BufferedImage rgbBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_BYTE_INDEXED, cm);
Graphics2D graphics2D = rgbBufferedImage.createGraphics();
graphics2D.drawImage(bufferedImage, 0, 0, newWidth, newHeight, null);
graphics2D.dispose();
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
writer.setOutput(new MemoryCacheImageOutputStream(baos));
IIOImage outputImage = new IIOImage(rgbBufferedImage, null, null);
try {
//writer.write(null, outputImage, jpgWriteParam);
writer.write(outputImage);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage(), e);
}
writer.dispose();
byte[] returnImage = null;
try {
baos.flush();
returnImage = baos.toByteArray();
baos.close();
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage(), e);
}
return returnImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment