How can I write metadata into a .JPG?

2019-05-28 23:35发布

问题:

I'm using this code to get these three diferent metadata attributes ('Object Name', 'ImageDescription' and 'Keywords') using the apache commons.imaging (snapshot). However, I have no clue about how to write into this attributes. Does anybody know the proper way? Thanks in advance...

IImageMetadata metadata = null;
String name;

try {
   metadata = Imaging.getMetadata(new File(filename));
} catch (ImageReadException | IOException e) {
}

if (metadata instanceof JpegImageMetadata) {
   final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
   final List<IImageMetadataItem> items = jpegMetadata.getItems();

   for (int i = 0; i < items.size(); i++) {
      final IImageMetadataItem item = items.get(i);
      name = item.toString().substring(0, item.toString().indexOf(":"));
      switch (name) {
      case "Object Name" :
      case "ImageDescription" :
      case "Keywords" :
         System.out.println(item.toString());
         break;
      }
   }
}

回答1:

The format overview page of apache.commons.imaging says that IPTC metadata writing is not supported but EXIF metadata writing is. For writing of EXIF metadata I also googled and found an example. So what you have to do is something along the lines:

final TiffImageMetadata exif = jpegMetadata.getExif();
TiffOutputSet outputSet = exif.getOutputSet();

then adding or removing and adding (=updating) tags and in the end:

new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);

with jpegImageFile a File (input) and os an OutputStream to the output file.