-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebPWrapper.cs
1976 lines (1830 loc) · 103 KB
/
WebPWrapper.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Wrapper for WebP format in C#. (MIT) Jose M. Piñeiro
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Decode Functions:
/// Bitmap Load(string pathFileName) - Load a WebP file in bitmap.
/// Bitmap Decode(byte[] rawWebP) - Decode WebP data (rawWebP) to bitmap.
/// Bitmap Decode(byte[] rawWebP, WebPDecoderOptions options) - Decode WebP data (rawWebP) to bitmap using 'options'.
/// Bitmap GetThumbnailFast(byte[] rawWebP, int width, int height) - Get a thumbnail from WebP data (rawWebP) with dimensions 'width x height'. Fast mode.
/// Bitmap GetThumbnailQuality(byte[] rawWebP, int width, int height) - Fast get a thumbnail from WebP data (rawWebP) with dimensions 'width x height'. Quality mode.
///
/// Encode Functions:
/// Save(Bitmap bmp, string pathFileName, int quality) - Save bitmap with quality lost to WebP file. Opcionally select 'quality'.
/// byte[] EncodeLossy(Bitmap bmp, int quality) - Encode bitmap with quality lost to WebP byte array. Opcionally select 'quality'.
/// byte[] EncodeLossy(Bitmap bmp, int quality, int speed, bool info) - Encode bitmap with quality lost to WebP byte array. Select 'quality', 'speed' and optionally select 'info'.
/// byte[] EncodeLossless(Bitmap bmp) - Encode bitmap without quality lost to WebP byte array.
/// byte[] EncodeLossless(Bitmap bmp, int speed, bool info = false) - Encode bitmap without quality lost to WebP byte array. Select 'speed'.
/// byte[] EncodeNearLossless(Bitmap bmp, int quality, int speed = 9, bool info = false) - Encode bitmap with a near lossless method to WebP byte array. Select 'quality', 'speed' and optionally select 'info'.
///
/// Another functions:
/// string GetVersion() - Get the library version
/// GetInfo(byte[] rawWebP, out int width, out int height, out bool has_alpha, out bool has_animation, out string format) - Get information of WEBP data
/// float[] PictureDistortion(Bitmap source, Bitmap reference, int metric_type) - Get PSNR, SSIM or LSIM distortion metric between two pictures
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows.Forms;
namespace UVTileDiscardMapper
{
public sealed class WebP : IDisposable
{
private const int WEBP_MAX_DIMENSION = 16383;
#region | Public Decode Functions |
/// <summary>Read a WebP file</summary>
/// <param name="pathFileName">WebP file to load</param>
/// <returns>Bitmap with the WebP image</returns>
public Bitmap Load(string pathFileName)
{
try
{
byte[] rawWebP = File.ReadAllBytes(pathFileName);
return Decode(rawWebP);
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.Load"); }
}
/// <summary>Decode a WebP image</summary>
/// <param name="rawWebP">The data to uncompress</param>
/// <returns>Bitmap with the WebP image</returns>
public Bitmap Decode(byte[] rawWebP)
{
Bitmap bmp = null;
BitmapData bmpData = null;
GCHandle pinnedWebP = GCHandle.Alloc(rawWebP, GCHandleType.Pinned);
try
{
//Get image width and height
GetInfo(rawWebP, out int imgWidth, out int imgHeight, out bool hasAlpha, out bool hasAnimation, out string format);
//Create a BitmapData and Lock all pixels to be written
if (hasAlpha)
bmp = new Bitmap(imgWidth, imgHeight, PixelFormat.Format32bppArgb);
else
bmp = new Bitmap(imgWidth, imgHeight, PixelFormat.Format24bppRgb);
bmpData = bmp.LockBits(new Rectangle(0, 0, imgWidth, imgHeight), ImageLockMode.WriteOnly, bmp.PixelFormat);
//Uncompress the image
int outputSize = bmpData.Stride * imgHeight;
IntPtr ptrData = pinnedWebP.AddrOfPinnedObject();
if (bmp.PixelFormat == PixelFormat.Format24bppRgb)
UnsafeNativeMethods.WebPDecodeBGRInto(ptrData, rawWebP.Length, bmpData.Scan0, outputSize, bmpData.Stride);
else
UnsafeNativeMethods.WebPDecodeBGRAInto(ptrData, rawWebP.Length, bmpData.Scan0, outputSize, bmpData.Stride);
return bmp;
}
catch (Exception) { throw; }
finally
{
//Unlock the pixels
if (bmpData != null)
bmp.UnlockBits(bmpData);
//Free memory
if (pinnedWebP.IsAllocated)
pinnedWebP.Free();
}
}
/// <summary>Decode a WebP image</summary>
/// <param name="rawWebP">the data to uncompress</param>
/// <param name="options">Options for advanced decode</param>
/// <returns>Bitmap with the WebP image</returns>
public Bitmap Decode(byte[] rawWebP, WebPDecoderOptions options, PixelFormat pixelFormat = PixelFormat.DontCare)
{
GCHandle pinnedWebP = GCHandle.Alloc(rawWebP, GCHandleType.Pinned);
Bitmap bmp = null;
BitmapData bmpData = null;
VP8StatusCode result;
try
{
WebPDecoderConfig config = new WebPDecoderConfig();
if (UnsafeNativeMethods.WebPInitDecoderConfig(ref config) == 0)
{
throw new Exception("WebPInitDecoderConfig failed. Wrong version?");
}
// Read the .webp input file information
IntPtr ptrRawWebP = pinnedWebP.AddrOfPinnedObject();
int height;
int width;
if (options.use_scaling == 0)
{
result = UnsafeNativeMethods.WebPGetFeatures(ptrRawWebP, rawWebP.Length, ref config.input);
if (result != VP8StatusCode.VP8_STATUS_OK)
throw new Exception("Failed WebPGetFeatures with error " + result);
//Test cropping values
if (options.use_cropping == 1)
{
if (options.crop_left + options.crop_width > config.input.Width || options.crop_top + options.crop_height > config.input.Height)
throw new Exception("Crop options exceeded WebP image dimensions");
width = options.crop_width;
height = options.crop_height;
}
}
else
{
width = options.scaled_width;
height = options.scaled_height;
}
config.options.bypass_filtering = options.bypass_filtering;
config.options.no_fancy_upsampling = options.no_fancy_upsampling;
config.options.use_cropping = options.use_cropping;
config.options.crop_left = options.crop_left;
config.options.crop_top = options.crop_top;
config.options.crop_width = options.crop_width;
config.options.crop_height = options.crop_height;
config.options.use_scaling = options.use_scaling;
config.options.scaled_width = options.scaled_width;
config.options.scaled_height = options.scaled_height;
config.options.use_threads = options.use_threads;
config.options.dithering_strength = options.dithering_strength;
config.options.flip = options.flip;
config.options.alpha_dithering_strength = options.alpha_dithering_strength;
//Create a BitmapData and Lock all pixels to be written
if (config.input.Has_alpha == 1)
{
config.output.colorspace = WEBP_CSP_MODE.MODE_bgrA;
bmp = new Bitmap(config.input.Width, config.input.Height, PixelFormat.Format32bppArgb);
}
else
{
config.output.colorspace = WEBP_CSP_MODE.MODE_BGR;
bmp = new Bitmap(config.input.Width, config.input.Height, PixelFormat.Format24bppRgb);
}
bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
// Specify the output format
config.output.u.RGBA.rgba = bmpData.Scan0;
config.output.u.RGBA.stride = bmpData.Stride;
config.output.u.RGBA.size = (UIntPtr)(bmp.Height * bmpData.Stride);
config.output.height = bmp.Height;
config.output.width = bmp.Width;
config.output.is_external_memory = 1;
// Decode
result = UnsafeNativeMethods.WebPDecode(ptrRawWebP, rawWebP.Length, ref config);
if (result != VP8StatusCode.VP8_STATUS_OK)
{
throw new Exception("Failed WebPDecode with error " + result);
}
UnsafeNativeMethods.WebPFreeDecBuffer(ref config.output);
return bmp;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.Decode"); }
finally
{
//Unlock the pixels
if (bmpData != null)
bmp.UnlockBits(bmpData);
//Free memory
if (pinnedWebP.IsAllocated)
pinnedWebP.Free();
}
}
/// <summary>Get Thumbnail from webP in mode faster/low quality</summary>
/// <param name="rawWebP">The data to uncompress</param>
/// <param name="width">Wanted width of thumbnail</param>
/// <param name="height">Wanted height of thumbnail</param>
/// <returns>Bitmap with the WebP thumbnail in 24bpp</returns>
public Bitmap GetThumbnailFast(byte[] rawWebP, int width, int height)
{
GCHandle pinnedWebP = GCHandle.Alloc(rawWebP, GCHandleType.Pinned);
Bitmap bmp = null;
BitmapData bmpData = null;
try
{
WebPDecoderConfig config = new WebPDecoderConfig();
if (UnsafeNativeMethods.WebPInitDecoderConfig(ref config) == 0)
throw new Exception("WebPInitDecoderConfig failed. Wrong version?");
// Set up decode options
config.options.bypass_filtering = 1;
config.options.no_fancy_upsampling = 1;
config.options.use_threads = 1;
config.options.use_scaling = 1;
config.options.scaled_width = width;
config.options.scaled_height = height;
// Create a BitmapData and Lock all pixels to be written
bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, bmp.PixelFormat);
// Specify the output format
config.output.colorspace = WEBP_CSP_MODE.MODE_BGR;
config.output.u.RGBA.rgba = bmpData.Scan0;
config.output.u.RGBA.stride = bmpData.Stride;
config.output.u.RGBA.size = (UIntPtr)(height * bmpData.Stride);
config.output.height = height;
config.output.width = width;
config.output.is_external_memory = 1;
// Decode
IntPtr ptrRawWebP = pinnedWebP.AddrOfPinnedObject();
VP8StatusCode result = UnsafeNativeMethods.WebPDecode(ptrRawWebP, rawWebP.Length, ref config);
if (result != VP8StatusCode.VP8_STATUS_OK)
throw new Exception("Failed WebPDecode with error " + result);
UnsafeNativeMethods.WebPFreeDecBuffer(ref config.output);
return bmp;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.Thumbnail"); }
finally
{
//Unlock the pixels
if (bmpData != null)
bmp.UnlockBits(bmpData);
//Free memory
if (pinnedWebP.IsAllocated)
pinnedWebP.Free();
}
}
/// <summary>Thumbnail from webP in mode slow/high quality</summary>
/// <param name="rawWebP">The data to uncompress</param>
/// <param name="width">Wanted width of thumbnail</param>
/// <param name="height">Wanted height of thumbnail</param>
/// <returns>Bitmap with the WebP thumbnail</returns>
public Bitmap GetThumbnailQuality(byte[] rawWebP, int width, int height)
{
GCHandle pinnedWebP = GCHandle.Alloc(rawWebP, GCHandleType.Pinned);
Bitmap bmp = null;
BitmapData bmpData = null;
try
{
WebPDecoderConfig config = new WebPDecoderConfig();
if (UnsafeNativeMethods.WebPInitDecoderConfig(ref config) == 0)
throw new Exception("WebPInitDecoderConfig failed. Wrong version?");
IntPtr ptrRawWebP = pinnedWebP.AddrOfPinnedObject();
VP8StatusCode result = UnsafeNativeMethods.WebPGetFeatures(ptrRawWebP, rawWebP.Length, ref config.input);
if (result != VP8StatusCode.VP8_STATUS_OK)
throw new Exception("Failed WebPGetFeatures with error " + result);
// Set up decode options
config.options.bypass_filtering = 0;
config.options.no_fancy_upsampling = 0;
config.options.use_threads = 1;
config.options.use_scaling = 1;
config.options.scaled_width = width;
config.options.scaled_height = height;
//Create a BitmapData and Lock all pixels to be written
if (config.input.Has_alpha == 1)
{
config.output.colorspace = WEBP_CSP_MODE.MODE_bgrA;
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
}
else
{
config.output.colorspace = WEBP_CSP_MODE.MODE_BGR;
bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
}
bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, bmp.PixelFormat);
// Specify the output format
config.output.u.RGBA.rgba = bmpData.Scan0;
config.output.u.RGBA.stride = bmpData.Stride;
config.output.u.RGBA.size = (UIntPtr)(height * bmpData.Stride);
config.output.height = height;
config.output.width = width;
config.output.is_external_memory = 1;
// Decode
result = UnsafeNativeMethods.WebPDecode(ptrRawWebP, rawWebP.Length, ref config);
if (result != VP8StatusCode.VP8_STATUS_OK)
throw new Exception("Failed WebPDecode with error " + result);
UnsafeNativeMethods.WebPFreeDecBuffer(ref config.output);
return bmp;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.Thumbnail"); }
finally
{
//Unlock the pixels
if (bmpData != null)
bmp.UnlockBits(bmpData);
//Free memory
if (pinnedWebP.IsAllocated)
pinnedWebP.Free();
}
}
#endregion
#region | Public Encode Functions |
/// <summary>Save bitmap to file in WebP format</summary>
/// <param name="bmp">Bitmap with the WebP image</param>
/// <param name="pathFileName">The file to write</param>
/// <param name="quality">Between 0 (lower quality, lowest file size) and 100 (highest quality, higher file size)</param>
public void Save(Bitmap bmp, string pathFileName, int quality = 75)
{
byte[] rawWebP;
try
{
//Encode in webP format
rawWebP = EncodeLossy(bmp, quality);
//Write webP file
File.WriteAllBytes(pathFileName, rawWebP);
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.Save"); }
}
/// <summary>Lossy encoding bitmap to WebP (Simple encoding API)</summary>
/// <param name="bmp">Bitmap with the image</param>
/// <param name="quality">Between 0 (lower quality, lowest file size) and 100 (highest quality, higher file size)</param>
/// <returns>Compressed data</returns>
public byte[] EncodeLossy(Bitmap bmp, int quality = 75)
{
//test bmp
if (bmp.Width == 0 || bmp.Height == 0)
throw new ArgumentException("Bitmap contains no data.", "bmp");
if (bmp.Width > WEBP_MAX_DIMENSION || bmp.Height > WEBP_MAX_DIMENSION)
throw new NotSupportedException("Bitmap's dimension is too large. Max is " + WEBP_MAX_DIMENSION + "x" + WEBP_MAX_DIMENSION + " pixels.");
if (bmp.PixelFormat != PixelFormat.Format24bppRgb && bmp.PixelFormat != PixelFormat.Format32bppArgb)
throw new NotSupportedException("Only support Format24bppRgb and Format32bppArgb pixelFormat.");
BitmapData bmpData = null;
IntPtr unmanagedData = IntPtr.Zero;
try
{
int size;
//Get bmp data
bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
//Compress the bmp data
if (bmp.PixelFormat == PixelFormat.Format24bppRgb)
size = UnsafeNativeMethods.WebPEncodeBGR(bmpData.Scan0, bmp.Width, bmp.Height, bmpData.Stride, quality, out unmanagedData);
else
size = UnsafeNativeMethods.WebPEncodeBGRA(bmpData.Scan0, bmp.Width, bmp.Height, bmpData.Stride, quality, out unmanagedData);
if (size == 0)
throw new Exception("Can´t encode WebP");
//Copy image compress data to output array
byte[] rawWebP = new byte[size];
Marshal.Copy(unmanagedData, rawWebP, 0, size);
return rawWebP;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.EncodeLossly"); }
finally
{
//Unlock the pixels
if (bmpData != null)
bmp.UnlockBits(bmpData);
//Free memory
if (unmanagedData != IntPtr.Zero)
UnsafeNativeMethods.WebPFree(unmanagedData);
}
}
/// <summary>Lossy encoding bitmap to WebP (Advanced encoding API)</summary>
/// <param name="bmp">Bitmap with the image</param>
/// <param name="quality">Between 0 (lower quality, lowest file size) and 100 (highest quality, higher file size)</param>
/// <param name="speed">Between 0 (fastest, lowest compression) and 9 (slower, best compression)</param>
/// <returns>Compressed data</returns>
public byte[] EncodeLossy(Bitmap bmp, int quality, int speed, bool info = false)
{
//Initialize configuration structure
WebPConfig config = new WebPConfig();
//Set compression parameters
if (UnsafeNativeMethods.WebPConfigInit(ref config, WebPPreset.WEBP_PRESET_DEFAULT, 75) == 0)
throw new Exception("Can´t configure preset");
// Add additional tuning:
config.method = speed;
if (config.method > 6)
config.method = 6;
config.quality = quality;
config.autofilter = 1;
config.pass = speed + 1;
config.segments = 4;
config.partitions = 3;
config.thread_level = 1;
config.alpha_quality = quality;
config.alpha_filtering = 2;
config.use_sharp_yuv = 1;
if (UnsafeNativeMethods.WebPGetDecoderVersion() > 1082) //Old version does not support preprocessing 4
{
config.preprocessing = 4;
config.use_sharp_yuv = 1;
}
else
config.preprocessing = 3;
return AdvancedEncode(bmp, config, info);
}
/// <summary>Lossless encoding bitmap to WebP (Simple encoding API)</summary>
/// <param name="bmp">Bitmap with the image</param>
/// <returns>Compressed data</returns>
public byte[] EncodeLossless(Bitmap bmp)
{
//test bmp
if (bmp.Width == 0 || bmp.Height == 0)
throw new ArgumentException("Bitmap contains no data.", "bmp");
if (bmp.Width > WEBP_MAX_DIMENSION || bmp.Height > WEBP_MAX_DIMENSION)
throw new NotSupportedException("Bitmap's dimension is too large. Max is " + WEBP_MAX_DIMENSION + "x" + WEBP_MAX_DIMENSION + " pixels.");
if (bmp.PixelFormat != PixelFormat.Format24bppRgb && bmp.PixelFormat != PixelFormat.Format32bppArgb)
throw new NotSupportedException("Only support Format24bppRgb and Format32bppArgb pixelFormat.");
BitmapData bmpData = null;
IntPtr unmanagedData = IntPtr.Zero;
try
{
//Get bmp data
bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
//Compress the bmp data
int size;
if (bmp.PixelFormat == PixelFormat.Format24bppRgb)
size = UnsafeNativeMethods.WebPEncodeLosslessBGR(bmpData.Scan0, bmp.Width, bmp.Height, bmpData.Stride, out unmanagedData);
else
size = UnsafeNativeMethods.WebPEncodeLosslessBGRA(bmpData.Scan0, bmp.Width, bmp.Height, bmpData.Stride, out unmanagedData);
//Copy image compress data to output array
byte[] rawWebP = new byte[size];
Marshal.Copy(unmanagedData, rawWebP, 0, size);
return rawWebP;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.EncodeLossless (Simple)"); }
finally
{
//Unlock the pixels
if (bmpData != null)
bmp.UnlockBits(bmpData);
//Free memory
if (unmanagedData != IntPtr.Zero)
UnsafeNativeMethods.WebPFree(unmanagedData);
}
}
/// <summary>Lossless encoding image in bitmap (Advanced encoding API)</summary>
/// <param name="bmp">Bitmap with the image</param>
/// <param name="speed">Between 0 (fastest, lowest compression) and 9 (slower, best compression)</param>
/// <returns>Compressed data</returns>
public byte[] EncodeLossless(Bitmap bmp, int speed)
{
//Initialize configuration structure
WebPConfig config = new WebPConfig();
//Set compression parameters
if (UnsafeNativeMethods.WebPConfigInit(ref config, WebPPreset.WEBP_PRESET_DEFAULT, (speed + 1) * 10) == 0)
throw new Exception("Can´t config preset");
//Old version of DLL does not support info and WebPConfigLosslessPreset
if (UnsafeNativeMethods.WebPGetDecoderVersion() > 1082)
{
if (UnsafeNativeMethods.WebPConfigLosslessPreset(ref config, speed) == 0)
throw new Exception("Can´t configure lossless preset");
}
else
{
config.lossless = 1;
config.method = speed;
if (config.method > 6)
config.method = 6;
config.quality = (speed + 1) * 10;
}
config.pass = speed + 1;
config.thread_level = 1;
config.alpha_filtering = 2;
config.use_sharp_yuv = 1;
config.exact = 0;
return AdvancedEncode(bmp, config, false);
}
/// <summary>Near lossless encoding image in bitmap</summary>
/// <param name="bmp">Bitmap with the image</param>
/// <param name="quality">Between 0 (lower quality, lowest file size) and 100 (highest quality, higher file size)</param>
/// <param name="speed">Between 0 (fastest, lowest compression) and 9 (slower, best compression)</param>
/// <returns>Compress data</returns>
public byte[] EncodeNearLossless(Bitmap bmp, int quality, int speed = 9)
{
//test DLL version
if (UnsafeNativeMethods.WebPGetDecoderVersion() <= 1082)
throw new Exception("This DLL version not support EncodeNearLossless");
//Inicialize config struct
WebPConfig config = new WebPConfig();
//Set compression parameters
if (UnsafeNativeMethods.WebPConfigInit(ref config, WebPPreset.WEBP_PRESET_DEFAULT, (speed + 1) * 10) == 0)
throw new Exception("Can´t configure preset");
if (UnsafeNativeMethods.WebPConfigLosslessPreset(ref config, speed) == 0)
throw new Exception("Can´t configure lossless preset");
config.pass = speed + 1;
config.near_lossless = quality;
config.thread_level = 1;
config.alpha_filtering = 2;
config.use_sharp_yuv = 1;
config.exact = 0;
return AdvancedEncode(bmp, config, false);
}
#endregion
#region | Another Public Functions |
/// <summary>Get the libwebp version</summary>
/// <returns>Version of library</returns>
public string GetVersion()
{
try
{
uint v = (uint)UnsafeNativeMethods.WebPGetDecoderVersion();
var revision = v % 256;
var minor = (v >> 8) % 256;
var major = (v >> 16) % 256;
return major + "." + minor + "." + revision;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.GetVersion"); }
}
/// <summary>Get info of WEBP data</summary>
/// <param name="rawWebP">The data of WebP</param>
/// <param name="width">width of image</param>
/// <param name="height">height of image</param>
/// <param name="has_alpha">Image has alpha channel</param>
/// <param name="has_animation">Image is a animation</param>
/// <param name="format">Format of image: 0 = undefined (/mixed), 1 = lossy, 2 = lossless</param>
public void GetInfo(byte[] rawWebP, out int width, out int height, out bool has_alpha, out bool has_animation, out string format)
{
VP8StatusCode result;
GCHandle pinnedWebP = GCHandle.Alloc(rawWebP, GCHandleType.Pinned);
try
{
IntPtr ptrRawWebP = pinnedWebP.AddrOfPinnedObject();
WebPBitstreamFeatures features = new WebPBitstreamFeatures();
result = UnsafeNativeMethods.WebPGetFeatures(ptrRawWebP, rawWebP.Length, ref features);
if (result != 0)
throw new Exception(result.ToString());
width = features.Width;
height = features.Height;
if (features.Has_alpha == 1) has_alpha = true; else has_alpha = false;
if (features.Has_animation == 1) has_animation = true; else has_animation = false;
switch (features.Format)
{
case 1:
format = "lossy";
break;
case 2:
format = "lossless";
break;
default:
format = "undefined";
break;
}
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.GetInfo"); }
finally
{
//Free memory
if (pinnedWebP.IsAllocated)
pinnedWebP.Free();
}
}
/// <summary>Compute PSNR, SSIM or LSIM distortion metric between two pictures. Warning: this function is rather CPU-intensive</summary>
/// <param name="source">Picture to measure</param>
/// <param name="reference">Reference picture</param>
/// <param name="metric_type">0 = PSNR, 1 = SSIM, 2 = LSIM</param>
/// <returns>dB in the Y/U/V/Alpha/All order</returns>
public float[] GetPictureDistortion(Bitmap source, Bitmap reference, int metric_type)
{
WebPPicture wpicSource = new WebPPicture();
WebPPicture wpicReference = new WebPPicture();
BitmapData sourceBmpData = null;
BitmapData referenceBmpData = null;
float[] result = new float[5];
GCHandle pinnedResult = GCHandle.Alloc(result, GCHandleType.Pinned);
try
{
if (source == null)
throw new Exception("Source picture is void");
if (reference == null)
throw new Exception("Reference picture is void");
if (metric_type > 2)
throw new Exception("Bad metric_type. Use 0 = PSNR, 1 = SSIM, 2 = LSIM");
if (source.Width != reference.Width || source.Height != reference.Height)
throw new Exception("Source and Reference pictures have different dimensions");
// Setup the source picture data, allocating the bitmap, width and height
sourceBmpData = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, source.PixelFormat);
wpicSource = new WebPPicture();
if (UnsafeNativeMethods.WebPPictureInitInternal(ref wpicSource) != 1)
throw new Exception("Can´t initialize WebPPictureInit");
wpicSource.width = (int)source.Width;
wpicSource.height = (int)source.Height;
//Put the source bitmap componets in wpic
if (sourceBmpData.PixelFormat == PixelFormat.Format32bppArgb)
{
wpicSource.use_argb = 1;
if (UnsafeNativeMethods.WebPPictureImportBGRA(ref wpicSource, sourceBmpData.Scan0, sourceBmpData.Stride) != 1)
throw new Exception("Can´t allocate memory in WebPPictureImportBGR");
}
else
{
wpicSource.use_argb = 0;
if (UnsafeNativeMethods.WebPPictureImportBGR(ref wpicSource, sourceBmpData.Scan0, sourceBmpData.Stride) != 1)
throw new Exception("Can´t allocate memory in WebPPictureImportBGR");
}
// Setup the reference picture data, allocating the bitmap, width and height
referenceBmpData = reference.LockBits(new Rectangle(0, 0, reference.Width, reference.Height), ImageLockMode.ReadOnly, reference.PixelFormat);
wpicReference = new WebPPicture();
if (UnsafeNativeMethods.WebPPictureInitInternal(ref wpicReference) != 1)
throw new Exception("Can´t initialize WebPPictureInit");
wpicReference.width = (int)reference.Width;
wpicReference.height = (int)reference.Height;
wpicReference.use_argb = 1;
//Put the source bitmap contents in WebPPicture instance
if (sourceBmpData.PixelFormat == PixelFormat.Format32bppArgb)
{
wpicSource.use_argb = 1;
if (UnsafeNativeMethods.WebPPictureImportBGRA(ref wpicReference, referenceBmpData.Scan0, referenceBmpData.Stride) != 1)
throw new Exception("Can´t allocate memory in WebPPictureImportBGR");
}
else
{
wpicSource.use_argb = 0;
if (UnsafeNativeMethods.WebPPictureImportBGR(ref wpicReference, referenceBmpData.Scan0, referenceBmpData.Stride) != 1)
throw new Exception("Can´t allocate memory in WebPPictureImportBGR");
}
//Measure
IntPtr ptrResult = pinnedResult.AddrOfPinnedObject();
if (UnsafeNativeMethods.WebPPictureDistortion(ref wpicSource, ref wpicReference, metric_type, ptrResult) != 1)
throw new Exception("Can´t measure.");
return result;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.GetPictureDistortion"); }
finally
{
//Unlock the pixels
if (sourceBmpData != null)
source.UnlockBits(sourceBmpData);
if (referenceBmpData != null)
reference.UnlockBits(referenceBmpData);
//Free memory
if (wpicSource.argb != IntPtr.Zero)
UnsafeNativeMethods.WebPPictureFree(ref wpicSource);
if (wpicReference.argb != IntPtr.Zero)
UnsafeNativeMethods.WebPPictureFree(ref wpicReference);
//Free memory
if (pinnedResult.IsAllocated)
pinnedResult.Free();
}
}
#endregion
#region | Private Methods |
/// <summary>Encoding image using Advanced encoding API</summary>
/// <param name="bmp">Bitmap with the image</param>
/// <param name="config">Configuration for encode</param>
/// <param name="info">True if need encode info.</param>
/// <returns>Compressed data</returns>
private byte[] AdvancedEncode(Bitmap bmp, WebPConfig config, bool info)
{
byte[] rawWebP = null;
byte[] dataWebp = null;
WebPPicture wpic = new WebPPicture();
BitmapData bmpData = null;
WebPAuxStats stats = new WebPAuxStats();
IntPtr ptrStats = IntPtr.Zero;
GCHandle pinnedArrayHandle = new GCHandle();
int dataWebpSize;
try
{
//Validate the configuration
if (UnsafeNativeMethods.WebPValidateConfig(ref config) != 1)
throw new Exception("Bad configuration parameters");
//test bmp
if (bmp.Width == 0 || bmp.Height == 0)
throw new ArgumentException("Bitmap contains no data.", "bmp");
if (bmp.Width > WEBP_MAX_DIMENSION || bmp.Height > WEBP_MAX_DIMENSION)
throw new NotSupportedException("Bitmap's dimension is too large. Max is " + WEBP_MAX_DIMENSION + "x" + WEBP_MAX_DIMENSION + " pixels.");
if (bmp.PixelFormat != PixelFormat.Format24bppRgb && bmp.PixelFormat != PixelFormat.Format32bppArgb)
throw new NotSupportedException("Only support Format24bppRgb and Format32bppArgb pixelFormat.");
// Setup the input data, allocating a the bitmap, width and height
bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
if (UnsafeNativeMethods.WebPPictureInitInternal(ref wpic) != 1)
throw new Exception("Can´t initialize WebPPictureInit");
wpic.width = (int)bmp.Width;
wpic.height = (int)bmp.Height;
wpic.use_argb = 1;
if (bmp.PixelFormat == PixelFormat.Format32bppArgb)
{
//Put the bitmap componets in wpic
int result = UnsafeNativeMethods.WebPPictureImportBGRA(ref wpic, bmpData.Scan0, bmpData.Stride);
if (result != 1)
throw new Exception("Can´t allocate memory in WebPPictureImportBGRA");
wpic.colorspace = (uint)WEBP_CSP_MODE.MODE_bgrA;
dataWebpSize = bmp.Width * bmp.Height * 32;
dataWebp = new byte[bmp.Width * bmp.Height * 32]; //Memory for WebP output
}
else
{
//Put the bitmap contents in WebPPicture instance
int result = UnsafeNativeMethods.WebPPictureImportBGR(ref wpic, bmpData.Scan0, bmpData.Stride);
if (result != 1)
throw new Exception("Can´t allocate memory in WebPPictureImportBGR");
dataWebpSize = bmp.Width * bmp.Height * 24;
}
//Set up statistics of compression
if (info)
{
stats = new WebPAuxStats();
ptrStats = Marshal.AllocHGlobal(Marshal.SizeOf(stats));
Marshal.StructureToPtr(stats, ptrStats, false);
wpic.stats = ptrStats;
}
//Memory for WebP output
if (dataWebpSize > 2147483591)
dataWebpSize = 2147483591;
dataWebp = new byte[bmp.Width * bmp.Height * 32];
pinnedArrayHandle = GCHandle.Alloc(dataWebp, GCHandleType.Pinned);
IntPtr initPtr = pinnedArrayHandle.AddrOfPinnedObject();
wpic.custom_ptr = initPtr;
//Set up a byte-writing method (write-to-memory, in this case)
UnsafeNativeMethods.OnCallback = new UnsafeNativeMethods.WebPMemoryWrite(MyWriter);
wpic.writer = Marshal.GetFunctionPointerForDelegate(UnsafeNativeMethods.OnCallback);
//compress the input samples
if (UnsafeNativeMethods.WebPEncode(ref config, ref wpic) != 1)
throw new Exception("Encoding error: " + ((WebPEncodingError)wpic.error_code).ToString());
//Remove OnCallback
UnsafeNativeMethods.OnCallback = null;
//Unlock the pixels
bmp.UnlockBits(bmpData);
bmpData = null;
//Copy webpData to rawWebP
int size = (int)((long)wpic.custom_ptr - (long)initPtr);
rawWebP = new byte[size];
Array.Copy(dataWebp, rawWebP, size);
//Remove compression data
pinnedArrayHandle.Free();
dataWebp = null;
//Show statistics
if (info)
{
stats = (WebPAuxStats)Marshal.PtrToStructure(ptrStats, typeof(WebPAuxStats));
MessageBox.Show("Dimension: " + wpic.width + " x " + wpic.height + " pixels\n" +
"Output: " + stats.coded_size + " bytes\n" +
"PSNR Y: " + stats.PSNRY + " db\n" +
"PSNR u: " + stats.PSNRU + " db\n" +
"PSNR v: " + stats.PSNRV + " db\n" +
"PSNR ALL: " + stats.PSNRALL + " db\n" +
"Block intra4: " + stats.block_count_intra4 + "\n" +
"Block intra16: " + stats.block_count_intra16 + "\n" +
"Block skipped: " + stats.block_count_skipped + "\n" +
"Header size: " + stats.header_bytes + " bytes\n" +
"Mode-partition: " + stats.mode_partition_0 + " bytes\n" +
"Macro-blocks 0: " + stats.segment_size_segments0 + " residuals bytes\n" +
"Macro-blocks 1: " + stats.segment_size_segments1 + " residuals bytes\n" +
"Macro-blocks 2: " + stats.segment_size_segments2 + " residuals bytes\n" +
"Macro-blocks 3: " + stats.segment_size_segments3 + " residuals bytes\n" +
"Quantizer 0: " + stats.segment_quant_segments0 + " residuals bytes\n" +
"Quantizer 1: " + stats.segment_quant_segments1 + " residuals bytes\n" +
"Quantizer 2: " + stats.segment_quant_segments2 + " residuals bytes\n" +
"Quantizer 3: " + stats.segment_quant_segments3 + " residuals bytes\n" +
"Filter level 0: " + stats.segment_level_segments0 + " residuals bytes\n" +
"Filter level 1: " + stats.segment_level_segments1 + " residuals bytes\n" +
"Filter level 2: " + stats.segment_level_segments2 + " residuals bytes\n" +
"Filter level 3: " + stats.segment_level_segments3 + " residuals bytes\n", "Compression statistics");
}
return rawWebP;
}
catch (Exception ex) { throw new Exception(ex.Message + "\r\nIn WebP.AdvancedEncode"); }
finally
{
//Free temporal compress memory
if (pinnedArrayHandle.IsAllocated)
{
pinnedArrayHandle.Free();
}
//Free statistics memory
if (ptrStats != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptrStats);
}
//Unlock the pixels
if (bmpData != null)
{
bmp.UnlockBits(bmpData);
}
//Free memory
if (wpic.argb != IntPtr.Zero)
{
UnsafeNativeMethods.WebPPictureFree(ref wpic);
}
}
}
private int MyWriter([InAttribute()] IntPtr data, UIntPtr data_size, ref WebPPicture picture)
{
UnsafeNativeMethods.CopyMemory(picture.custom_ptr, data, (uint)data_size);
//picture.custom_ptr = IntPtr.Add(picture.custom_ptr, (int)data_size); //Only in .NET > 4.0
picture.custom_ptr = new IntPtr(picture.custom_ptr.ToInt64() + (int)data_size);
return 1;
}
private delegate int MyWriterDelegate([InAttribute()] IntPtr data, UIntPtr data_size, ref WebPPicture picture);
#endregion
#region | Destruction |
/// <summary>Free memory</summary>
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
}
#region | Import libwebp functions |
[SuppressUnmanagedCodeSecurityAttribute]
internal sealed partial class UnsafeNativeMethods
{
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
internal static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
private static readonly int WEBP_DECODER_ABI_VERSION = 0x0208;
/// <summary>This function will initialize the configuration according to a predefined set of parameters (referred to by 'preset') and a given quality factor</summary>
/// <param name="config">The WebPConfig structure</param>
/// <param name="preset">Type of image</param>
/// <param name="quality">Quality of compression</param>
/// <returns>0 if error</returns>
internal static int WebPConfigInit(ref WebPConfig config, WebPPreset preset, float quality)
{
switch (IntPtr.Size)
{
case 4:
return WebPConfigInitInternal_x86(ref config, preset, quality, WEBP_DECODER_ABI_VERSION);
case 8:
return WebPConfigInitInternal_x64(ref config, preset, quality, WEBP_DECODER_ABI_VERSION);
default:
throw new InvalidOperationException("Invalid platform. Can not find proper function");
}
}
[DllImport("libwebp_x86.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPConfigInitInternal")]
private static extern int WebPConfigInitInternal_x86(ref WebPConfig config, WebPPreset preset, float quality, int WEBP_DECODER_ABI_VERSION);
[DllImport("libwebp_x64.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPConfigInitInternal")]
private static extern int WebPConfigInitInternal_x64(ref WebPConfig config, WebPPreset preset, float quality, int WEBP_DECODER_ABI_VERSION);
/// <summary>Get info of WepP image</summary>
/// <param name="rawWebP">Bytes[] of WebP image</param>
/// <param name="data_size">Size of rawWebP</param>
/// <param name="features">Features of WebP image</param>
/// <returns>VP8StatusCode</returns>
internal static VP8StatusCode WebPGetFeatures(IntPtr rawWebP, int data_size, ref WebPBitstreamFeatures features)
{
switch (IntPtr.Size)
{
case 4:
return WebPGetFeaturesInternal_x86(rawWebP, (UIntPtr)data_size, ref features, WEBP_DECODER_ABI_VERSION);
case 8:
return WebPGetFeaturesInternal_x64(rawWebP, (UIntPtr)data_size, ref features, WEBP_DECODER_ABI_VERSION);
default:
throw new InvalidOperationException("Invalid platform. Can not find proper function");
}
}
[DllImport("libwebp_x86.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPGetFeaturesInternal")]
private static extern VP8StatusCode WebPGetFeaturesInternal_x86([InAttribute()] IntPtr rawWebP, UIntPtr data_size, ref WebPBitstreamFeatures features, int WEBP_DECODER_ABI_VERSION);
[DllImport("libwebp_x64.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPGetFeaturesInternal")]
private static extern VP8StatusCode WebPGetFeaturesInternal_x64([InAttribute()] IntPtr rawWebP, UIntPtr data_size, ref WebPBitstreamFeatures features, int WEBP_DECODER_ABI_VERSION);
/// <summary>Activate the lossless compression mode with the desired efficiency</summary>
/// <param name="config">The WebPConfig struct</param>
/// <param name="level">between 0 (fastest, lowest compression) and 9 (slower, best compression)</param>
/// <returns>0 in case of parameter error</returns>
internal static int WebPConfigLosslessPreset(ref WebPConfig config, int level)
{
switch (IntPtr.Size)
{
case 4:
return WebPConfigLosslessPreset_x86(ref config, level);
case 8:
return WebPConfigLosslessPreset_x64(ref config, level);
default:
throw new InvalidOperationException("Invalid platform. Can not find proper function");
}
}
[DllImport("libwebp_x86.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPConfigLosslessPreset")]
private static extern int WebPConfigLosslessPreset_x86(ref WebPConfig config, int level);
[DllImport("libwebp_x64.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPConfigLosslessPreset")]
private static extern int WebPConfigLosslessPreset_x64(ref WebPConfig config, int level);
/// <summary>Check that configuration is non-NULL and all configuration parameters are within their valid ranges</summary>
/// <param name="config">The WebPConfig structure</param>
/// <returns>1 if configuration is OK</returns>
internal static int WebPValidateConfig(ref WebPConfig config)
{
switch (IntPtr.Size)
{
case 4:
return WebPValidateConfig_x86(ref config);
case 8:
return WebPValidateConfig_x64(ref config);
default:
throw new InvalidOperationException("Invalid platform. Can not find proper function");
}
}
[DllImport("libwebp_x86.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPValidateConfig")]
private static extern int WebPValidateConfig_x86(ref WebPConfig config);
[DllImport("libwebp_x64.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPValidateConfig")]
private static extern int WebPValidateConfig_x64(ref WebPConfig config);
/// <summary>Initialize the WebPPicture structure checking the DLL version</summary>
/// <param name="wpic">The WebPPicture structure</param>
/// <returns>1 if not error</returns>
internal static int WebPPictureInitInternal(ref WebPPicture wpic)
{
switch (IntPtr.Size)
{
case 4:
return WebPPictureInitInternal_x86(ref wpic, WEBP_DECODER_ABI_VERSION);
case 8:
return WebPPictureInitInternal_x64(ref wpic, WEBP_DECODER_ABI_VERSION);
default: