How to Add 'Comments' to a JPEG File Using C#

后端 未结 6 1321
眼角桃花
眼角桃花 2020-11-27 17:59

Within the property window of a JPEG image, there is a tab called \'Summary\'. Within this tab, there is a field called \'Comments\' I would like to write some c# code which

6条回答
  •  时光说笑
    2020-11-27 18:30

    Thanks to the answers here, I've coded a solution to set a comment using memory only:

    public static Image SetImageComment(Image image, string comment) {
      using (var memStream = new MemoryStream()) {
        image.Save(memStream, ImageFormat.Jpeg);
        memStream.Position = 0;
        var decoder = new JpegBitmapDecoder(memStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
        BitmapMetadata metadata;
        if (decoder.Metadata == null) {
          metadata = new BitmapMetadata("jpg");
        } else {
          metadata = decoder.Metadata;
        }
    
        metadata.Comment = comment;
    
        var bitmapFrame = decoder.Frames[0];
        BitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metadata, bitmapFrame.ColorContexts));
    
        var imageStream = new MemoryStream();
        encoder.Save(imageStream);
        imageStream.Position = 0;
        image.Dispose();
        image = null;
        return Image.FromStream(imageStream);
      }
    }
    

    Don't forget to dispose the image that is returned by this method. (For example after saving the image to a file)

提交回复
热议问题