我目前正在使用 javax.imageio.ImageIO 编写 PNG 文件。我想包括一个文本 block (实际上是任何 block listed here ),但看不到这样做的方法。
从 com.sun.imageio.plugins.png.PNGMetadata 的外观来看,这应该是可能的。
如有任何线索或答案,我将不胜感激。
M.
最佳答案
我经过一些反编译后想到的解决方案如下......
RenderedImage image = getMyImage();
Iterator<ImageWriter> iterator = ImageIO.getImageWritersBySuffix( "png" );
if(!iterator.hasNext()) throw new Error( "No image writer for PNG" );
ImageWriter imagewriter = iterator.next();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imagewriter.setOutput( ImageIO.createImageOutputStream( bytes ) );
// Create & populate metadata
PNGMetadata metadata = new PNGMetadata();
// see http://www.w3.org/TR/PNG-Chunks.html#C.tEXt for standardized keywords
metadata.tEXt_keyword.add( "Title" );
metadata.tEXt_text.add( "Mandelbrot" );
metadata.tEXt_keyword.add( "Comment" );
metadata.tEXt_text.add( "..." );
metadata.tEXt_keyword.add( "MandelbrotCoords" ); // custom keyword
metadata.tEXt_text.add( fractal.getCoords().toString() );
// Render the PNG to memory
IIOImage iioImage = new IIOImage( image, null, null );
iioImage.setMetadata( metadata ); // Attach the metadata
imagewriter.write( null, iioImage, null );
关于java - 如何从 Java 中保存带有 tEXt 或 iTXt block 的 PNG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/721918/