0

I am trying to read a comment from a JPEG file into a text box. I know how to write a comment using the following code:

public void addImageComment(string imageFlePath, string comments)
{
BitmapDecoder decoder = null;
BitmapFrame bitmapFrame = null;
BitmapMetadata metadata = null;
FileInfo originalImage = new FileInfo(imageFlePath);

if (File.Exists(imageFlePath))
{
    // load the jpg file with a JpegBitmapDecoder    
    using (Stream jpegStreamIn = File.Open(imageFlePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
    {
        decoder = new JpegBitmapDecoder(jpegStreamIn, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
    }

    bitmapFrame = decoder.Frames[0];
    metadata = (BitmapMetadata)bitmapFrame.Metadata;

    if (bitmapFrame != null)
    {
        BitmapMetadata metaData = (BitmapMetadata)bitmapFrame.Metadata.Clone();

        if (metaData != null)
        {
            // modify the metadata   
            metaData.Comment = comments;

            // get an encoder to create a new jpg file with the new metadata.      
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metaData, bitmapFrame.ColorContexts));
            //string jpegNewFileName = Path.Combine(jpegDirectory, "JpegTemp.jpg");

            // Delete the original
            originalImage.Delete();

            // Save the new image 
            using (Stream jpegStreamOut = File.Open(imageFlePath, FileMode.CreateNew, FileAccess.ReadWrite))
            {
                encoder.Save(jpegStreamOut);
            }
        }
    }
}

}

What I am trying to do is to READ the existing comment, not write a new one. Everything I find says to use the code above to read the comment, but I don't understand how to do that. Can someone please help me with this? Please be as detailed as possible so I can learn how this works.

Tornado726
  • 352
  • 1
  • 7
  • 16
  • 1
    I would expect right after this line `metadata = (BitmapMetadata)bitmapFrame.Metadata;` the `comment` property on that Metadata instance should have a value, assuming a comment has been set on the file. – rene Aug 19 '23 at 05:21
  • I didn't write the code myself. I got it from https://stackoverflow.com/questions/1755185/how-to-add-comments-to-a-jpeg-file-using-c-sharp – Tornado726 Aug 19 '23 at 23:54

0 Answers0