【问题标题】:How can I write metadata to png Image如何将元数据写入 png 图像
【发布时间】:2014-03-17 07:58:49
【问题描述】:

我一直在尝试找到一种将元数据写入 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;
}

但这无济于事。

我已经尝试使用Writing image metadata in Java, preferably PNG的答案

这可行(有点),但我的读取功能看不到它。

【问题讨论】:

    标签: java image png metadata


    【解决方案1】:

    如果你想添加一个块到图像,你必须读取和写入完整的图像。示例

    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();
    

    如果您需要更高的性能,可以在较低级别读取/写入块,请参阅this example

    【讨论】:

    • 这样我们需要提供一个目标文件,如果我想将元数据写入同一个文件以创建新文件。
    • @AnkeshkumarJaisansaria 您写入其他文件并重命名它。相信我,没有别的办法。
    • 好的。。谢谢你的回答。
    • 我所做的是给 DesFile 与 Original 相同的路径。这样做效果很好,但文件创建日期更改为当前日期。那么如何解决呢?
    【解决方案2】:

    试试这个:

    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();
    

    【讨论】:

    • 我需要设置一个chunk Key和Value。所以我的阅读功能会找到它。
    猜你喜欢
    • 1970-01-01
    • 2013-02-19
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2019-05-14
    • 2017-09-15
    相关资源
    最近更新 更多