有没有一种简单的方法可以减少 IndexedColorModel 中的颜色数量?
我有一个大的 8 位 PNG 图像.我正在使用 Java 将图像切成较小的 32x32 图像.我使用 Java 的 ImageIO
将 PNG 加载到 BufferedImage
中,然后将其称为 getSubimage(x, y, 32, 32)
.然后我使用 ImageIO
将每个图块写成 PNG.
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.
问题是生成的图像与原始图像具有相同的 IndexColorModel
.例如,一个 32x32 的图块总共只有 8 种颜色,但它包含一个颜色模型,其中包含来自原始图像的所有 100 多种颜色.
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.
我想在写出 PNG 之前从 32x32 磁贴的 IndexColorModel
中删除未使用的颜色.包含图像中未使用的颜色的颜色数据是没有意义的,我希望图像尽可能小.
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.
是否有内置机制可以做到这一点,或者有人可以指出一种(简单的)方法来修改/减少 ColorModel
?
Is there a built-in mechanism to do this or can someone point me to an (easy) way to modify/reduce the ColorModel
?
谢谢!
看看java.awt.image中的ColorConvertOp
.
Take a look at ColorConvertOp
in java.awt.image.
基本上,您创建所需深度的新 IndexColorModel
.如果你真的想要最小的,你可以遍历 Raster
并计算颜色.否则,只需选择每像素 4 或 5 位.然后使用 TYPE_BYTE_BINARY
和 IndexColorMap
创建一个 BufferedImage
.最后,使用ColorConvertOp
的filter()
方法将原始数据复制到新的BufferedImage
.
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
.