开发者

Is there an easy way to reduce the number of colors in an IndexedColorModel?

开发者 https://www.devze.com 2022-12-13 06:13 出处:网络
I have a large 8-bit PNG image.I am using Java to slice the image into smaller 32x32 images.I use Java\'s ImageIO to load the PNG into a BufferedImage and then call it\'s getSubimage(x, y, 32, 32).I t

I have a large 8-bit PNG image. I am using Java to slice the image into smaller 32x32 images. I use Java's ImageIO to load the PNG into a BufferedImage and then call it's getSubimage(x, y, 32, 32). I then use ImageIO to write each tile out as a PNG.

The problem is that the resulting image has the same IndexColorModel as the original image. For example, one 32x32 tile has only 8 total colors but it includes a color model with all 100-odd colors from the original image.

I would like to remove unused colors from the 32x32 tile's IndexColorModel before I write out the PNG. There is no sense including color data for colors not used in the image and I'd like the images to be as small as possible.

Is there a built-in mechanism to do this or can someone point me to an (easy) way to modify/reduce th开发者_C百科e ColorModel?

Thanks!


Take a look at ColorConvertOp in java.awt.image.

Basically, you create a new IndexColorModel of the desired depth. If you really want the smallest, you can walk through the Raster and count the colors. Otherwise, just choose 4 or 5 bits per pixel. Then create a BufferedImage with TYPE_BYTE_BINARY and the IndexColorMap. Finally, use the ColorConvertOp's filter() method to copy the original data to the new BufferedImage.

0

精彩评论

暂无评论...
验证码 换一张
取 消