I've been stumped trying to figure this one out.
I'm trying to retrieve the "Jpeg Comment" out of a jpg file via C#. The code below works but I need the basic comment NOT the Exif comment. I'm using FastStone Image Viewer to set the basic comment. Help me retrieve it.
I can use the commandline program exiv2 to verify that the comment is there. exiv2 -pc c:\t开发者_如何学Goest.jpg (it spits out the basic comment). exiv2 -pa c:\test.jpg (it spits out the EXIF comment) I've used several C# libs to get at it but they get the EXIF data.
Image x = Image.FromFile(@"c:\test.jpg");
PropertyItem prop;
prop = x.GetPropertyItem(0x9286);
string Comment = Encoding.ASCII.GetString(prop.Value);
You could refer to this link.
(Thanks for those who already have answered the same question, although the answer was quite right but not 100% to solve this problem.)
Here are three steps you need to do:
- Be aware that you should have the Jpeg file cloned.
- Set the comment of the cloned file.
- Replace the file by deleting the original jpeg file.
Here is the sample 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);
}
}
}
}
}
You can do this quite simply with the MetadataExtractor library (available via NuGet):
JpegCommentDirectory jpegCommentDirectory = ImageMetadataReader.ReadMetadata(imagePath)
.OfType<JpegCommentDirectory>()
.FirstOrDefault();
string comment = jpegCommentDirectory?.GetDescription(JpegCommentDirectory.TagComment);
精彩评论