java 在java中,如何将java.awt.image.BufferedImage写入8位png文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/266486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In java, how do you write a java.awt.image.BufferedImage to an 8-bit png file?
提问by
I am trying to write out a png file from a java.awt.image.BufferedImage. Everything works fine but the resulting png is a 32-bit file.
我正在尝试从 java.awt.image.BufferedImage 写出一个 png 文件。一切正常,但生成的 png 是 32 位文件。
Is there a way to make the png file be 8-bit? The image is grayscale, but I do need transparency as this is an overlay image. I am using java 6, and I would prefer to return an OutputStream so that I can have the calling class deal with writing out the file to disk/db.
有没有办法使png文件成为8位?图像是灰度的,但我确实需要透明度,因为这是一个叠加图像。我使用的是 java 6,我更愿意返回一个 OutputStream,这样我就可以让调用类处理将文件写到磁盘/数据库。
Here is the relevant portion of the code:
这是代码的相关部分:
public static ByteArrayOutputStream createImage(InputStream originalStream)
throws IOException {
ByteArrayOutputStream oStream = null;
java.awt.Image newImg = javax.imageio.ImageIO.read(originalStream);
int imgWidth = newImg.getWidth(null);
int imgHeight = newImg.getHeight(null);
java.awt.image.BufferedImage bim = new java.awt.image.BufferedImage(imgWidth,
imgHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB);
Color bckgrndColor = new Color(0x80, 0x80, 0x80);
Graphics2D gf = (Graphics2D)bim.getGraphics();
// set transparency for fill image
gf.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
gf.setColor(bckgrndColor);
gf.fillRect(0, 0, imgWidth, imgHeight);
oStream = new ByteArrayOutputStream();
javax.imageio.ImageIO.write(bim, "png", oStream);
oStream.close();
return oStream;
}
回答by kasperjj
The build in imageio png writer will write 32bit png files on all the platforms I have used it on, no matter what the source image is. You should also be aware that many people have complained that the resulting compression is much lower than what is possible with the png format. There are several independent png librariesavailable that allow you to specify the exact format, but I don't actually have any experience with any of them.
内置的 imageio png writer 将在我使用过的所有平台上写入 32 位 png 文件,无论源图像是什么。您还应该知道,许多人抱怨所得到的压缩比使用 png 格式可能得到的压缩要低得多。有几个独立的png 库可让您指定确切的格式,但我实际上对它们中的任何一个都没有任何经验。
回答by PhiLho
It is an interesting question... It is late, I will experiment tomorrow. I will first try and use a BufferedImage.TYPE_BYTE_INDEXED (perhaps after drawing) to see if Java is smart enough to generate an 8bit PNG.
Or perhaps some image library can allow that.
这是一个有趣的问题... 晚了,我明天再实验。我将首先尝试使用 BufferedImage.TYPE_BYTE_INDEXED(可能在绘制之后)来查看 Java 是否足够智能以生成 8 位 PNG。
或者也许某些图像库可以允许。
[EDIT] Some years later... Actually, I made the code at the time, but forgot to update this thread... I used the code pointed at by Kat, with a little refinement on the handling of transparency, and saving in PNG format instead of Gif format. It works in making a 8-bit PNG file with all-or-nothing transparency.
[编辑] 几年后...其实我当时写了代码,但忘了更新这个线程...我使用了 Kat 指向的代码,在处理透明度上做了一些改进,并保存在PNG 格式而不是 Gif 格式。它用于制作具有全有或全无透明度的 8 位 PNG 文件。
You can find a working test file at http://bazaar.launchpad.net/~philho/+junk/Java/view/head:/Tests/src/org/philhosoft/tests/image/AddTransparency.javausing my ImageUtilclass.
您可以 使用我的ImageUtil类在http://bazaar.launchpad.net/~philho/+junk/Java/view/head:/Tests/src/org/philhosoft/tests/image/AddTransparency.java找到一个工作测试文件.
Since the code isn't that big, for posterity sake, I post it here, without the JavaDoc to save some lines.
由于代码不是那么大,为了后代的缘故,我把它贴在这里,没有 JavaDoc 以节省一些行。
public class ImageUtil
{
public static int ALPHA_BIT_MASK = 0xFF000000;
public static BufferedImage imageToBufferedImage(Image image, int width, int height)
{
return imageToBufferedImage(image, width, height, BufferedImage.TYPE_INT_ARGB);
}
public static BufferedImage imageToBufferedImage(Image image, int width, int height, int type)
{
BufferedImage dest = new BufferedImage(width, height, type);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
return dest;
}
public static BufferedImage convertRGBAToIndexed(BufferedImage srcImage)
{
// Create a non-transparent palletized image
Image flattenedImage = transformTransparencyToMagenta(srcImage);
BufferedImage flatImage = imageToBufferedImage(flattenedImage,
srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
BufferedImage destImage = makeColorTransparent(flatImage, 0, 0);
return destImage;
}
private static Image transformTransparencyToMagenta(BufferedImage image)
{
ImageFilter filter = new RGBImageFilter()
{
@Override
public final int filterRGB(int x, int y, int rgb)
{
int pixelValue = 0;
int opacity = (rgb & ALPHA_BIT_MASK) >>> 24;
if (opacity < 128)
{
// Quite transparent: replace color with transparent magenta
// (traditional color for binary transparency)
pixelValue = 0x00FF00FF;
}
else
{
// Quite opaque: get pure color
pixelValue = (rgb & 0xFFFFFF) | ALPHA_BIT_MASK;
}
return pixelValue;
}
};
ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
public static BufferedImage makeColorTransparent(BufferedImage image, int x, int y)
{
ColorModel cm = image.getColorModel();
if (!(cm instanceof IndexColorModel))
return image; // No transparency added as we don't have an indexed image
IndexColorModel originalICM = (IndexColorModel) cm;
WritableRaster raster = image.getRaster();
int colorIndex = raster.getSample(x, y, 0); // colorIndex is an offset in the palette of the ICM'
// Number of indexed colors
int size = originalICM.getMapSize();
byte[] reds = new byte[size];
byte[] greens = new byte[size];
byte[] blues = new byte[size];
originalICM.getReds(reds);
originalICM.getGreens(greens);
originalICM.getBlues(blues);
IndexColorModel newICM = new IndexColorModel(8, size, reds, greens, blues, colorIndex);
return new BufferedImage(newICM, raster, image.isAlphaPremultiplied(), null);
}
}
回答by PhiLho
I found the answer as to how to convert RGBA to Indexed here: http://www.eichberger.de/2007/07/transparent-gifs-in-java.html
我在这里找到了关于如何将 RGBA 转换为索引的答案:http: //www.eichberger.de/2007/07/transparent-gifs-in-java.html
However, the resulting 8-bit png file only has 100% or 0% transparency. You could probably tweak the IndexColorModel arrays, but we have decided to make the generated file (what was an overlay mask) into an underlay jpg and use what was the static base as the transparent overlay.
但是,生成的 8 位 png 文件只有 100% 或 0% 的透明度。您可能可以调整 IndexColorModel 数组,但我们决定将生成的文件(什么是覆盖蒙版)制作为底层 jpg,并使用静态基础作为透明覆盖。
回答by PhiLho
Thanks for responding, I was going to try an TYPE_BYTE_INDEXEDwith an IndexColorModel and may still but if ImageIO writes out 32-bit regardless it appears that I may be wasting my time there.
感谢您的回复,我打算尝试TYPE_BYTE_INDEXED使用 IndexColorModel 并且可能仍然如此,但是如果 ImageIO 写出 32 位,不管看起来我可能在那里浪费时间。
The image I am trying to write out can be very large (up to 8000x4000) but is just a simple mask for the image underneath, so will only have a ~30% transparent gray and a 100% transparent cutout. I would use a GIF but IE6 seems to have trouble with displaying one that large.
我试图写出的图像可能非常大(高达 8000x4000),但只是下面图像的简单蒙版,因此只有 ~30% 的透明灰色和 100% 透明的切口。我会使用 GIF,但 IE6 似乎无法显示那么大的 GIF。
It only gets generated once and in an internal set-up type screen, so performance isn't an issue either, but it does have to be done within the java code and not by an offline utility.
它只在内部设置类型屏幕中生成一次,因此性能也不是问题,但它必须在 java 代码中完成,而不是由离线实用程序完成。
The libraries that you specified might be used to transform it while writing... I am going to go check that out.
您指定的库可能用于在编写时对其进行转换...我要去检查一下。
If anyone has a better way, please let me know!!
如果有人有更好的方法,请告诉我!!
Thanks!
谢谢!

