Created
August 15, 2021 01:09
-
-
Save aaronmbos/29ca86e4d4316574ea536ded0ab3a9a8 to your computer and use it in GitHub Desktop.
ImageSharp and IPTC Metadata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Xml.Linq; | |
using System; | |
using System.Threading.Tasks; | |
using SixLabors.ImageSharp; | |
using SixLabors.ImageSharp.Metadata.Profiles.Iptc; | |
using System.Linq; | |
namespace ImageMetadata | |
{ | |
class Program | |
{ | |
private static readonly string _fileName = "pokemon.jpg"; | |
static async Task Main(string[] args) | |
{ | |
using (var image = await Image.LoadAsync($"./{_fileName}")) | |
{ | |
ReadMetadata(image); | |
WriteMetadata(image); | |
ReadMetadata(image); | |
await image.SaveAsJpegAsync("./pokemon-metadata.jpg"); | |
} | |
Console.ReadKey(); | |
} | |
private static void ReadMetadata(Image image) | |
{ | |
if (image.Metadata.IptcProfile?.Values?.Any() ?? false) | |
{ | |
foreach (var prop in image.Metadata.IptcProfile.Values) | |
Console.WriteLine($"{prop.Tag}: {prop.Value}"); | |
} | |
else | |
Console.WriteLine($"{_fileName} does not contain metadata{Environment.NewLine}"); | |
} | |
private static void WriteMetadata(Image image) | |
{ | |
if (image.Metadata.IptcProfile == null) | |
image.Metadata.IptcProfile = new IptcProfile(); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Name, "Pokemon"); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Byline, "Thimo Pedersen"); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Caption, "Classic Pokeball Toy on a bunch of Pokemon Cards. Zapdos, Ninetales and a Trainercard visible."); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Source, @"https://rb.gy/hgkqhy"); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Keywords, "Pokemon"); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Keywords, "Pokeball"); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Keywords, "Cards"); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Keywords, "Zapdos"); | |
image.Metadata.IptcProfile.SetValue(IptcTag.Keywords, "Ninetails"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment