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

∥☆過路亽.° 提交于 2019-12-08 08:04:06

问题


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 the ColorModel?

Thanks!


回答1:


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.



来源:https://stackoverflow.com/questions/1836199/is-there-an-easy-way-to-reduce-the-number-of-colors-in-an-indexedcolormodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!