From 5a4a2e1023aee0e1ae02e9d4d6c70d24fcbc8e63 Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Wed, 29 Jul 2020 13:52:09 +0100 Subject: [PATCH] Sanitize metadata on jpeg save. Fixes #811 --- .../Imaging/Formats/JpegFormat.cs | 19 +++++++++++++++++++ .../MetaData/ExifPropertyTagConstants.cs | 5 +++++ 2 files changed, 24 insertions(+) diff --git a/src/ImageProcessor/Imaging/Formats/JpegFormat.cs b/src/ImageProcessor/Imaging/Formats/JpegFormat.cs index 882e80fac..ababe8679 100644 --- a/src/ImageProcessor/Imaging/Formats/JpegFormat.cs +++ b/src/ImageProcessor/Imaging/Formats/JpegFormat.cs @@ -11,10 +11,12 @@ namespace ImageProcessor.Imaging.Formats { using System; + using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; + using ImageProcessor.Imaging.MetaData; /// /// Provides the necessary information to support jpeg images. @@ -66,6 +68,8 @@ public sealed class JpegFormat : FormatBase /// public override Image Save(Stream stream, Image image, long bitDepth) { + SantizeMetadata(image); + // Jpegs can be saved with different settings to include a quality setting for the JPEG compression. // This improves output compression and quality. using (EncoderParameters encoderParameters = FormatUtilities.GetEncodingParameters(this.Quality)) @@ -97,6 +101,8 @@ public override Image Save(Stream stream, Image image, long bitDepth) /// public override Image Save(string path, Image image, long bitDepth) { + SantizeMetadata(image); + // Jpegs can be saved with different settings to include a quality setting for the JPEG compression. // This improves output compression and quality. using (EncoderParameters encoderParameters = FormatUtilities.GetEncodingParameters(this.Quality)) @@ -112,5 +118,18 @@ public override Image Save(string path, Image image, long bitDepth) return image; } + + // System.Drawing's jpeg encoder throws when proprietory tags are included in the metadata + // https://github.com/JimBobSquarePants/ImageProcessor/issues/811 + private static void SantizeMetadata(Image image) + { + foreach (int id in image.PropertyIdList) + { + if (Array.IndexOf(ExifPropertyTagConstants.Ids, id) == -1) + { + image.RemovePropertyItem(id); + } + } + } } } \ No newline at end of file diff --git a/src/ImageProcessor/Imaging/MetaData/ExifPropertyTagConstants.cs b/src/ImageProcessor/Imaging/MetaData/ExifPropertyTagConstants.cs index 4b8522e98..e9e67c4f3 100644 --- a/src/ImageProcessor/Imaging/MetaData/ExifPropertyTagConstants.cs +++ b/src/ImageProcessor/Imaging/MetaData/ExifPropertyTagConstants.cs @@ -83,5 +83,10 @@ public static class ExifPropertyTagConstants /// Gets all known property items /// public static readonly ExifPropertyTag[] All = (ExifPropertyTag[])Enum.GetValues(typeof(ExifPropertyTag)); + + /// + /// Gets the ids of all valid EXIF property items. + /// + public static readonly int[] Ids = Enum.GetValues(typeof(ExifPropertyTag)).Cast().ToArray(); } }