如何使用Java中的tEXt或iTXt块保存PNG? [英] How can I save a PNG with a tEXt or iTXt chunk from Java?

查看:180
本文介绍了如何使用Java中的tEXt或iTXt块保存PNG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用javax.imageio.ImageIO来编写PNG文件。我想要包含一个tEXt块(实际上是此处列出的任何块),但是看不到这样做的方法。

I am currently using javax.imageio.ImageIO to write a PNG file. I would like to include a tEXt chunk (and indeed any of the chunks listed here), but can see no means of doing so.

通过com.sun.imageio.plugins.png.PNGMetadata的外观,它应该是可能的。

By the looks of com.sun.imageio.plugins.png.PNGMetadata it should be possible.

我应该非常感谢任何线索或答案。

I should be most grateful for any clues or answers.

M。

推荐答案

我在一些反编译后遇到的解决方案如下......

The solution I struck upon after some decompilation, goes as follows ...

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中的tEXt或iTXt块保存PNG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆