Skip to content
This repository has been archived by the owner on Sep 6, 2023. It is now read-only.

Commit

Permalink
Sanitize metadata on jpeg save. Fixes #811
Browse files Browse the repository at this point in the history
  • Loading branch information
JimBobSquarePants committed Jul 29, 2020
1 parent d7d4260 commit 5a4a2e1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/ImageProcessor/Imaging/Formats/JpegFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// Provides the necessary information to support jpeg images.
Expand Down Expand Up @@ -66,6 +68,8 @@ public sealed class JpegFormat : FormatBase
/// </returns>
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))
Expand Down Expand Up @@ -97,6 +101,8 @@ public override Image Save(Stream stream, Image image, long bitDepth)
/// </returns>
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))
Expand All @@ -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);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,10 @@ public static class ExifPropertyTagConstants
/// Gets all known property items
/// </summary>
public static readonly ExifPropertyTag[] All = (ExifPropertyTag[])Enum.GetValues(typeof(ExifPropertyTag));

/// <summary>
/// Gets the ids of all valid EXIF property items.
/// </summary>
public static readonly int[] Ids = Enum.GetValues(typeof(ExifPropertyTag)).Cast<int>().ToArray();
}
}

0 comments on commit 5a4a2e1

Please sign in to comment.