A while ago I was working on a new feature of a CG project that involved loading hundreds of textures from disk. So far, so good. The images, however, were like an order from the devil: I needed RGBA images, but the images were all in BMP format (no chance for alpha channels) and splitted. How great is that?! To solve this problem, I had two alternatives: the first was joining and converting the images manually. If you consider the amount of images (422) and the average time to join and convert them (aprox. 3 minutes), that would take more than 21 hours (assuming the bore factor wouldn’t spoil my productivity in the meanwhile). Fortunately, there was a second alternative: automating the whole process. As I could not find a program that could supply my very specific need, I knew I had to make a little program for that, and there came JAI for the rescue. I took almost an hour googling, reading API docs and trying different commands until I found the ones I needed to create an alpha channel from a color and saving the image to PNG format as below:
/**
* Reads an image from disk and exports it to PNG format using alphaColor
as the transparent color.
*
* @param alphaColor the color to use as the trasparent color
* @param src the path of the source image
* @param dst the destination path of the exported image
*/
void toPNG(Color alphaColor, String src, String dst) {
RenderedImage image = JAI.create("fileload", src);
PNGEncodeParam.RGB param = new PNGEncodeParam.RGB();
param.setTransparentRGB(new int[]{alphaColor.getRed(), alphaColor.getGreen(),alphaColor.getBlue()});
JAI.create("filestore", image, dst, "PNG", param);
}
The resize code:
/**
* Reads an image from the given src
and writes it to the
* given dst
resized to the given width
and
* height
.
*
* @param src the path of the source image
* @param dst the destination path of the exported image
* @param width the width of the new image
* @param height the height of the new image
*/
void writeResizedPNGImage(String src, String dst, int width, int height) {
RenderedImage image = JAI.create("fileload", src);
BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = buf.createGraphics();
AffineTransform transform = new AffineTransform();
// Resize to fit
transform.setToScale(width / (double) image.getWidth(), height / (double) image.getHeight());
g.drawRenderedImage(image, transform);
JAI.create("filestore", buf, dst, "PNG");
}
Useful links: JAI download. JAI API docs.
Thanks for posting this. JAI is pretty good, but the documentation is horrible! It’s nice to find code snippets that do exactly what you need.