简体   繁体   中英

How to save additional information in the metadata of a jpg file with the System.Drawing.Bitmap class

I would like to know how to add additional information in a jpg file, I want to do it in the following way, once the file sequence has been created to save it where I want to automatically add the properties that I need to the metadata, I have two methods, one to save the property and another to get the value of that property, at the moment I'm only interested in the one it saves, but I don't know how to implement it to save the information, can someone help me with this problem please, it's the first time I've had to do something like that

I am guided by the following example Adding extra info to an image file

Class ModifyMetadata

protected void DownloadToFile(DownloadInfo Info, string filepath)
    {
        using (var stream = new SDKStream(filepath, FileCreateDisposition.CreateAlways, FileAccess.ReadWrite))
        {
            DownloadData(Info, stream.Reference);

            stream.Close();

            var bitmap = new Bitmap(filepath);

            var newMetadata = Extensions.SetMetaValue(bitmap, MetaProperty.Title, "Esto es un titulo para la imagen");

            bitmap.Save(newMetadata);
        }
    }

It looks like you need to do bitmap.Save(filepath); as the result of the extension function is just the same bitmap you give it (it's a "fluent" function).

Other notes:

  • bitmap needs a using .
  • The file remains open until the bitmap is disposed, so you need to copy it to a separate MemoryStream first. If you were saving to a different location then you don't need to do this.
  • You don't need to read bitmaps from files, you can pass a MemoryStream directly to new Bitmap() . This also means you don't need to worry about the file already being open. I'm not sure whether SDKStream supports writing to a MemoryStream though, but if so then you can also remove the stream copying.
  • That's not how extension functions should be used, you are supposed to do bitmap.SetMetaValue(MetaProperty.Title, ...
protected void DownloadToFile(DownloadInfo Info, string filepath)
{
    using (var stream = new SDKStream(filepath, FileCreateDisposition.CreateAlways, FileAccess.ReadWrite))
    {
        DownloadData(Info, stream.Reference);
    }

    using (var file = new FileStream(filepath))
    using (var memory = new MemoryStream(file.Length))
    {
        file.CopyTo(memory);
        file.Close();  // must close file before resaving
        using var bitmap = new Bitmap(filepath);
        {
            bitmap.SetMetaValue(MetaProperty.Title, "Esto es un titulo para la imagen");
            bitmap.Save(newMetadata);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM