如何将元数据写入 png 图像



我一直在尝试找到一种将元数据写入PNG的方法,并且尝试了很多。

我可以使用 pngj 库使用以下方法读取数据:

PngReader pngr = new PngReader(file);
pngr.readSkippingAllRows(); // reads only metadata
for (PngChunk c : pngr.getChunksList().getChunks()) {
    if (!ChunkHelper.isText(c))   continue;
        PngChunkTextVar ct = (PngChunkTextVar) c;
        String key = ct.getKey();
        String val = ct.getVal();
        System.out.print(key + " " + val + "n" );     
    }
pngr.close();

而且效果很好。但我需要写信给它。

我试过:

    public boolean writeCustomData(String key, String value) throws Exception {
    PngReader pngr = new PngReader(currentImage);
    PngWriter png = new PngWriter(new FileOutputStream(currentImage), pngr.imgInfo);
    png.getMetadata().setText(key, value);
    return true;
}

但这无济于事。

我尝试使用用 Java 编写图像元数据(最好是 PNG)中的答案

这有效(有点),但我的读取函数看不到它。

如果要

向映像添加块,则必须读取和写入完整映像。例

PngReader pngr = new PngReader(origFile);
PngWriter pngw = new PngWriter(destFile, pngr.imgInfo, true);
// instruct the writer to copy all ancillary chunks from source
pngw.copyChunksFrom(pngr.getChunksList(), ChunkCopyBehaviour.COPY_ALL);
// add a new textual chunk (can also be done after writing the rows)
pngw.getMetadata().setText("my key", "my val");
// copy all rows
for (int row = 0; row < pngr.imgInfo.rows; row++) {
  IImageLine l1 = pngr.readRow();
  pngw.writeRow(l1);
}
pngr.end(); 
pngw.end();

如果需要更高的性能,可以在较低级别读取/写入块,请参阅此示例。

试试这个:

Stream pngStream = new System.IO.FileStream("smiley.png", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
PngBitmapDecoder pngDecoder = new PngBitmapDecoder(pngStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapFrame pngFrame = pngDecoder.Frames[0];
InPlaceBitmapMetadataWriter pngInplace = pngFrame.CreateInPlaceBitmapMetadataWriter();
if (pngInplace.TrySave() == true)
{
    pngInplace.SetQuery("/Text/Description", "Have a nice day."); 
}
pngStream.Close();

最新更新