forked from 0xC0000054/pdn-webp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebPFile.cs
360 lines (313 loc) · 13.7 KB
/
WebPFile.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
////////////////////////////////////////////////////////////////////////
//
// This file is part of pdn-webp, a FileType plugin for Paint.NET
// that loads and saves WebP images.
//
// Copyright (c) 2011-2019 Nicholas Hayes
//
// This file is licensed under the MIT License.
// See LICENSE.txt for complete licensing and attribution information.
//
////////////////////////////////////////////////////////////////////////
using PaintDotNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using WebPFileType.Exif;
using WebPFileType.Properties;
namespace WebPFileType
{
internal static class WebPFile
{
/// <summary>
/// Gets the color profile from the WebP image.
/// </summary>
/// <param name="webpBytes">The WebP image data.</param>
/// <returns>
/// A byte array containing the color profile, if present; otherwise, <see langword="null"/>
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="webpBytes"/> is null.</exception>
internal static byte[] GetColorProfileBytes(byte[] webpBytes)
{
return GetMetadataBytes(webpBytes, WebPNative.MetadataType.ColorProfile);
}
/// <summary>
/// Gets the EXIF data from the WebP image.
/// </summary>
/// <param name="webpBytes">The WebP image data.</param>
/// <returns>
/// A byte array containing the EXIF data, if present; otherwise, <see langword="null"/>
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="webpBytes"/> is null.</exception>
internal static byte[] GetExifBytes(byte[] webpBytes)
{
return GetMetadataBytes(webpBytes, WebPNative.MetadataType.EXIF);
}
/// <summary>
/// Gets the XMP data from the WebP image.
/// </summary>
/// <param name="webpBytes">The WebP image data.</param>
/// <returns>
/// A byte array containing the XMP data, if present; otherwise, <see langword="null"/>
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="webpBytes"/> is null.</exception>
internal static byte[] GetXmpBytes(byte[] webpBytes)
{
return GetMetadataBytes(webpBytes, WebPNative.MetadataType.XMP);
}
/// <summary>
/// The WebP load function.
/// </summary>
/// <param name="webpBytes">The input image data</param>
/// <returns>
/// A <see cref="Bitmap"/> containing the WebP image.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="webpBytes"/> is null.</exception>
/// <exception cref="OutOfMemoryException">Insufficient memory to load the WebP image.</exception>
/// <exception cref="WebPException">
/// The WebP image is invalid.
/// -or-
/// A native API parameter is invalid.
/// </exception>
internal static unsafe Bitmap Load(byte[] webpBytes)
{
if (webpBytes == null)
{
throw new ArgumentNullException(nameof(webpBytes));
}
int width;
int height;
if (!WebPNative.WebPGetDimensions(webpBytes, out width, out height))
{
throw new WebPException(Resources.InvalidWebPImage);
}
Bitmap image = null;
Bitmap temp = null;
try
{
temp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
BitmapData bitmapData = temp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
try
{
WebPNative.WebPLoad(webpBytes, bitmapData);
}
finally
{
temp.UnlockBits(bitmapData);
}
image = temp;
temp = null;
}
finally
{
if (temp != null)
{
temp.Dispose();
}
}
return image;
}
/// <summary>
/// The WebP save function.
/// </summary>
/// <param name="input">The input Document.</param>
/// <param name="output">The output Stream.</param>
/// <param name="quality">The WebP save quality.</param>
/// <param name="preset">The WebP encoding preset.</param>
/// <param name="keepMetadata"><c>true</c> if metadata should be preserved; otherwise <c>false</c>.</param>
/// <param name="scratchSurface">The scratch surface.</param>
/// <param name="progressCallback">The progress callback.</param>
/// <exception cref="FormatException">The image exceeds 16383 pixels in width and/or height.</exception>
/// <exception cref="OutOfMemoryException">Insufficient memory to save the image.</exception>
/// <exception cref="WebPException">The encoder returned a non-memory related error.</exception>
internal static void Save(
Document input,
Stream output,
int quality,
WebPPreset preset,
bool keepMetadata,
Surface scratchSurface,
ProgressEventHandler progressCallback)
{
if (input.Width > WebPNative.WebPMaxDimension || input.Height > WebPNative.WebPMaxDimension)
{
throw new FormatException(Resources.InvalidImageDimensions);
}
WebPNative.EncodeParams encParams = new WebPNative.EncodeParams
{
quality = quality,
preset = preset
};
using (RenderArgs ra = new RenderArgs(scratchSurface))
{
input.Render(ra, true);
}
WebPNative.MetadataParams metadata = null;
if (keepMetadata)
{
metadata = CreateWebPMetadata(input, scratchSurface);
}
WebPNative.WebPReportProgress encProgress = null;
if (progressCallback != null)
{
encProgress = delegate(int percent)
{
try
{
progressCallback(null, new ProgressEventArgs(percent, true));
return true;
}
catch (OperationCanceledException)
{
return false;
}
};
}
WebPNative.WebPSave(scratchSurface, output, encParams, metadata, encProgress);
}
private static WebPNative.MetadataParams CreateWebPMetadata(Document doc, Surface scratchSurface)
{
byte[] iccProfileBytes = null;
byte[] exifBytes = null;
byte[] xmpBytes = null;
string colorProfile = doc.Metadata.GetUserValue(WebPMetadataNames.ColorProfile);
if (!string.IsNullOrEmpty(colorProfile))
{
iccProfileBytes = Convert.FromBase64String(colorProfile);
}
string exif = doc.Metadata.GetUserValue(WebPMetadataNames.EXIF);
if (!string.IsNullOrEmpty(exif))
{
exifBytes = Convert.FromBase64String(exif);
}
string xmp = doc.Metadata.GetUserValue(WebPMetadataNames.XMP);
if (!string.IsNullOrEmpty(xmp))
{
xmpBytes = Convert.FromBase64String(xmp);
}
if (iccProfileBytes == null || exifBytes == null)
{
Dictionary<MetadataKey, MetadataEntry> propertyItems = GetMetadataFromDocument(doc);
if (propertyItems != null)
{
ExifColorSpace exifColorSpace = ExifColorSpace.Srgb;
if (iccProfileBytes != null)
{
exifColorSpace = ExifColorSpace.Uncalibrated;
}
else
{
MetadataKey iccProfileKey = MetadataKeys.Image.InterColorProfile;
if (propertyItems.TryGetValue(iccProfileKey, out MetadataEntry iccProfileItem))
{
iccProfileBytes = iccProfileItem.GetData();
propertyItems.Remove(iccProfileKey);
exifColorSpace = ExifColorSpace.Uncalibrated;
}
}
if (exifBytes == null)
{
exifBytes = new ExifWriter(doc, propertyItems, exifColorSpace).CreateExifBlob();
}
}
}
if (iccProfileBytes != null || exifBytes != null || xmpBytes != null)
{
return new WebPNative.MetadataParams(iccProfileBytes, exifBytes, xmpBytes);
}
return null;
}
private static Dictionary<MetadataKey, MetadataEntry> GetMetadataFromDocument(Document doc)
{
Dictionary<MetadataKey, MetadataEntry> items = null;
Metadata metadata = doc.Metadata;
#if PDN_3_5_X
string[] exifKeys = metadata.GetKeys(Metadata.ExifSectionName);
if (exifKeys.Length > 0)
{
items = new Dictionary<MetadataKey, MetadataEntry>(exifKeys.Length);
foreach (string key in exifKeys)
{
string blob = metadata.GetValue(Metadata.ExifSectionName, key);
try
{
PropertyItem pi = PaintDotNet.SystemLayer.PdnGraphics.DeserializePropertyItem(blob);
MetadataKey metadataKey = new MetadataKey(ExifTagHelper.GuessTagSection(pi), (ushort)pi.Id);
if (!items.ContainsKey(metadataKey))
{
items.Add(metadataKey, new MetadataEntry(metadataKey, (TagDataType)pi.Type, pi.Value));
}
}
catch
{
// Ignore any items that cannot be deserialized.
}
}
}
#else
PaintDotNet.Imaging.ExifPropertyItem[] exifProperties = metadata.GetExifPropertyItems();
if (exifProperties.Length > 0)
{
items = new Dictionary<MetadataKey, MetadataEntry>(exifProperties.Length);
foreach (PaintDotNet.Imaging.ExifPropertyItem property in exifProperties)
{
MetadataSection section;
switch (property.Path.Section)
{
case PaintDotNet.Imaging.ExifSection.Image:
section = MetadataSection.Image;
break;
case PaintDotNet.Imaging.ExifSection.Photo:
section = MetadataSection.Exif;
break;
case PaintDotNet.Imaging.ExifSection.Interop:
section = MetadataSection.Interop;
break;
case PaintDotNet.Imaging.ExifSection.GpsInfo:
section = MetadataSection.Gps;
break;
default:
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.InvariantCulture,
"Unexpected {0} type: {1}",
nameof(PaintDotNet.Imaging.ExifSection),
(int)property.Path.Section));
}
MetadataKey metadataKey = new MetadataKey(section, property.Path.TagID);
if (!items.ContainsKey(metadataKey))
{
byte[] clonedData = PaintDotNet.Collections.EnumerableExtensions.ToArrayEx(property.Value.Data);
items.Add(metadataKey, new MetadataEntry(metadataKey, (TagDataType)property.Value.Type, clonedData));
}
}
}
#endif
return items;
}
/// <summary>
/// Gets the metadata from the WebP image.
/// </summary>
/// <param name="webpBytes">The WebP image data.</param>
/// <param name="type">The metadata type.</param>
/// <returns>
/// A byte array containing the requested metadata, if present; otherwise, <see langword="null"/>
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="webpBytes"/> is null.</exception>
private static byte[] GetMetadataBytes(byte[] webpBytes, WebPNative.MetadataType type)
{
if (webpBytes == null)
{
throw new ArgumentNullException(nameof(webpBytes));
}
byte[] bytes = null;
uint size = WebPNative.GetMetadataSize(webpBytes, type);
if (size > 0)
{
bytes = new byte[size];
WebPNative.ExtractMetadata(webpBytes, type, bytes, size);
}
return bytes;
}
}
}