This repository has been archived by the owner on Nov 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Image.cs
659 lines (577 loc) · 25.7 KB
/
Image.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
// AForge Image Processing Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2005-2011
// contacts@aforgenet.com
//
namespace Accord.Imaging
{
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using AForge;
using System.Net;
using Accord.Imaging.Formats;
/// <summary>
/// Core image relatad methods.
/// </summary>
///
/// <remarks>All methods of this class are static and represent general routines
/// used by different image processing classes.</remarks>
///
public static class Image
{
/// <summary>
/// Check if specified 8 bpp image is grayscale.
/// </summary>
///
/// <param name="image">Image to check.</param>
///
/// <returns>Returns <b>true</b> if the image is grayscale or <b>false</b> otherwise.</returns>
///
/// <remarks>The methods checks if the image is a grayscale image of 256 gradients.
/// The method first examines if the image's pixel format is
/// <see cref="System.Drawing.Imaging.PixelFormat">Format8bppIndexed</see>
/// and then it examines its palette to check if the image is grayscale or not.</remarks>
///
/// <seealso cref="IsColor8bpp(Bitmap)"/>
///
public static bool IsGrayscale(this Bitmap image)
{
// check pixel format
if (image.PixelFormat == PixelFormat.Format8bppIndexed)
{
// check palette
ColorPalette cp = image.Palette;
// init palette
for (int i = 0; i < 256; i++)
{
Color c = cp.Entries[i];
if ((c.R != i) || (c.G != i) || (c.B != i))
return false;
}
return true;
}
return false;
}
/// <summary>
/// Check if specified 8 bpp image is contains color-indexed pixels instead of intensity values.
/// </summary>
///
/// <param name="image">Image to check.</param>
///
/// <returns>Returns <b>true</b> if the image is color-indexed or <b>false</b> otherwise.</returns>
///
/// <seealso cref="IsGrayscale(Bitmap)"/>
///
public static bool IsColor8bpp(this Bitmap image)
{
if (image.PixelFormat != PixelFormat.Format8bppIndexed)
return false;
return !image.IsGrayscale();
}
/// <summary>
/// Create and initialize new 8 bpp grayscale image.
/// </summary>
///
/// <param name="width">Image width.</param>
/// <param name="height">Image height.</param>
///
/// <returns>Returns the created grayscale image.</returns>
///
/// <remarks>The method creates new 8 bpp grayscale image and initializes its palette.
/// Grayscale image is represented as
/// <see cref="System.Drawing.Imaging.PixelFormat">Format8bppIndexed</see>
/// image with palette initialized to 256 gradients of gray color.</remarks>
///
public static Bitmap CreateGrayscaleImage(int width, int height)
{
// create new image
Bitmap image = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
// set palette to grayscale
SetGrayscalePalette(image);
// return new image
return image;
}
/// <summary>
/// Set pallete of the 8 bpp indexed image to grayscale.
/// </summary>
///
/// <param name="image">Image to initialize.</param>
///
/// <remarks>The method initializes palette of
/// <see cref="System.Drawing.Imaging.PixelFormat">Format8bppIndexed</see>
/// image with 256 gradients of gray color.</remarks>
///
/// <exception cref="UnsupportedImageFormatException">Provided image is not 8 bpp indexed image.</exception>
///
public static void SetGrayscalePalette(this Bitmap image)
{
// check pixel format
if (image.PixelFormat != PixelFormat.Format8bppIndexed)
throw new UnsupportedImageFormatException("Source image is not 8 bpp image.");
// get palette
ColorPalette cp = image.Palette;
// init palette
for (int i = 0; i < 256; i++)
cp.Entries[i] = Color.FromArgb(i, i, i);
// set palette back
image.Palette = cp;
}
/// <summary>
/// Clone image.
/// </summary>
///
/// <param name="source">Source image.</param>
/// <param name="format">Pixel format of result image.</param>
///
/// <returns>Returns clone of the source image with specified pixel format.</returns>
///
/// <remarks>The original <see cref="System.Drawing.Bitmap.Clone(System.Drawing.Rectangle, System.Drawing.Imaging.PixelFormat)">Bitmap.Clone()</see>
/// does not produce the desired result - it does not create a clone with specified pixel format.
/// More of it, the original method does not create an actual clone - it does not create a copy
/// of the image. That is why this method was implemented to provide the functionality.</remarks>
///
public static Bitmap Clone(this Bitmap source, PixelFormat format)
{
// copy image if pixel format is the same
if (source.PixelFormat == format)
return Clone(source);
int width = source.Width;
int height = source.Height;
// create new image with desired pixel format
Bitmap bitmap = new Bitmap(width, height, format);
// draw source image on the new one using Graphics
using (Graphics g = Graphics.FromImage(bitmap))
g.DrawImage(source, 0, 0, width, height);
return bitmap;
}
/// <summary>
/// Clone image.
/// </summary>
///
/// <param name="bytes">Source image as an array of bytes.</param>
///
/// <returns>Returns clone of the source image with specified pixel format.</returns>
///
/// <remarks>The original <see cref="System.Drawing.Bitmap.Clone(System.Drawing.Rectangle, System.Drawing.Imaging.PixelFormat)">Bitmap.Clone()</see>
/// does not produce the desired result - it does not create a clone with specified pixel format.
/// More of it, the original method does not create an actual clone - it does not create a copy
/// of the image. That is why this method was implemented to provide the functionality.</remarks>
///
public static Bitmap Clone(this byte[] bytes)
{
return (Bitmap)Bitmap.FromStream(new MemoryStream(bytes));
}
/// <summary>
/// Clone image.
/// </summary>
///
/// <param name="source">Source image.</param>
///
/// <returns>Return clone of the source image.</returns>
///
/// <remarks>The original <see cref="System.Drawing.Bitmap.Clone(System.Drawing.Rectangle, System.Drawing.Imaging.PixelFormat)">Bitmap.Clone()</see>
/// does not produce the desired result - it does not create an actual clone (it does not create a copy
/// of the image). That is why this method was implemented to provide the functionality.</remarks>
///
public static Bitmap Clone(this Bitmap source)
{
// lock source bitmap data
BitmapData sourceData = source.LockBits(ImageLockMode.ReadOnly);
Bitmap destination;
try
{
// create new image
destination = Clone(sourceData);
}
finally
{
// unlock source image
source.UnlockBits(sourceData);
}
if (
(source.PixelFormat == PixelFormat.Format1bppIndexed) ||
(source.PixelFormat == PixelFormat.Format4bppIndexed) ||
(source.PixelFormat == PixelFormat.Format8bppIndexed) ||
(source.PixelFormat == PixelFormat.Indexed))
{
ColorPalette srcPalette = source.Palette;
ColorPalette dstPalette = destination.Palette;
// copy pallete
for (int i = 0; i < dstPalette.Entries.Length; i++)
dstPalette.Entries[i] = srcPalette.Entries[i];
destination.Palette = dstPalette;
}
return destination;
}
/// <summary>
/// Converts a 8-bpp color image into a 8-bpp grayscale image, setting its color
/// palette to grayscale and replacing palette indices with their grayscale values.
/// </summary>
///
/// <param name="bitmap">The bitmap to be converted.</param>
///
public static void ConvertColor8bppToGrayscale8bpp(this Bitmap bitmap)
{
if (bitmap.PixelFormat != PixelFormat.Format8bppIndexed)
throw new UnsupportedImageFormatException("Only 8-bpp images are supported.");
// lock source bitmap data
BitmapData sourceData = bitmap.LockBits(ImageLockMode.ReadWrite);
ColorPalette palette = bitmap.Palette;
int height = bitmap.Height;
int width = bitmap.Width;
int stride = sourceData.Stride;
int offset = stride - width;
try
{
unsafe
{
// base pointers
byte* src = (byte*)sourceData.Scan0.ToPointer();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, src++)
{
Color entry = palette.Entries[*src];
#if DEBUG
if (entry.R != entry.G || entry.R != entry.B)
throw new Exception();
#endif
*src = entry.R;
}
src += offset;
}
}
}
finally
{
// unlock source image
bitmap.UnlockBits(sourceData);
}
SetGrayscalePalette(bitmap);
}
/// <summary>
/// Clone image.
/// </summary>
///
/// <param name="sourceData">Source image data.</param>
///
/// <returns>Clones image from source image data. The message does not clone pallete in the
/// case if the source image has indexed pixel format.</returns>
///
public static Bitmap Clone(this BitmapData sourceData)
{
// get source image size
int width = sourceData.Width;
int height = sourceData.Height;
// create new image
Bitmap destination = new Bitmap(width, height, sourceData.PixelFormat);
// lock destination bitmap data
BitmapData destinationData = destination.LockBits(ImageLockMode.WriteOnly);
System.Diagnostics.Debug.Assert(destinationData.Stride == sourceData.Stride);
Accord.SystemTools.CopyUnmanagedMemory(
destinationData.Scan0, sourceData.Scan0, height * sourceData.Stride);
// unlock destination image
destination.UnlockBits(destinationData);
return destination;
}
/// <summary>
/// Format an image.
/// </summary>
///
/// <param name="image">Source image to format.</param>
///
/// <remarks><para>Formats the image to one of the formats, which are supported
/// by the <b>AForge.Imaging</b> library. The image is left untouched in the
/// case if it is already of
/// <see cref="System.Drawing.Imaging.PixelFormat">Format24bppRgb</see> or
/// <see cref="System.Drawing.Imaging.PixelFormat">Format32bppRgb</see> or
/// <see cref="System.Drawing.Imaging.PixelFormat">Format32bppArgb</see> or
/// <see cref="System.Drawing.Imaging.PixelFormat">Format48bppRgb</see> or
/// <see cref="System.Drawing.Imaging.PixelFormat">Format64bppArgb</see>
/// format or it is <see cref="IsGrayscale">grayscale</see>, otherwise the image
/// is converted to <see cref="System.Drawing.Imaging.PixelFormat">Format24bppRgb</see>
/// format.</para>
///
/// <para><note>The method is deprecated and <see cref="Clone(Bitmap, PixelFormat)"/> method should
/// be used instead with specifying desired pixel format.</note></para>
/// </remarks>
///
[Obsolete("Use Clone(Bitmap, PixelFormat) method instead and specify desired pixel format")]
public static void FormatImage(ref Bitmap image)
{
if (
(image.PixelFormat != PixelFormat.Format24bppRgb) &&
(image.PixelFormat != PixelFormat.Format32bppRgb) &&
(image.PixelFormat != PixelFormat.Format32bppArgb) &&
(image.PixelFormat != PixelFormat.Format48bppRgb) &&
(image.PixelFormat != PixelFormat.Format64bppArgb) &&
(image.PixelFormat != PixelFormat.Format16bppGrayScale) &&
(IsGrayscale(image) == false)
)
{
Bitmap tmp = image;
// convert to 24 bits per pixel
image = Clone(tmp, PixelFormat.Format24bppRgb);
// delete old image
tmp.Dispose();
}
}
/// <summary>
/// Load bitmap from file.
/// </summary>
///
/// <param name="fileName">File name to load bitmap from.</param>
///
/// <returns>Returns loaded bitmap.</returns>
///
/// <remarks><para>The method is provided as an alternative of <see cref="System.Drawing.Image.FromFile(string)"/>
/// method to solve the issues of locked file. The standard .NET's method locks the source file until
/// image's object is disposed, so the file can not be deleted or overwritten. This method workarounds the issue and
/// does not lock the source file.</para>
/// </remarks>
///
/// <example>
/// <code source="Unit Tests\Accord.Tests.Imaging\Formats\PNMCodecTest.cs" region="doc_load" />
/// </example>
///
public static System.Drawing.Bitmap FromFile(string fileName)
{
return ImageDecoder.DecodeFromFile(fileName);
}
/// <summary>
/// Convert bitmap with 16 bits per plane to a bitmap with 8 bits per plane.
/// </summary>
///
/// <param name="bitmap">Source image to convert.</param>
///
/// <returns>Returns new image which is a copy of the source image but with 8 bits per plane.</returns>
///
/// <remarks><para>The routine does the next pixel format conversions:
/// <list type="bullet">
/// <item><see cref="PixelFormat.Format16bppGrayScale">Format16bppGrayScale</see> to
/// <see cref="PixelFormat.Format8bppIndexed">Format8bppIndexed</see> with grayscale palette;</item>
/// <item><see cref="PixelFormat.Format48bppRgb">Format48bppRgb</see> to
/// <see cref="PixelFormat.Format24bppRgb">Format24bppRgb</see>;</item>
/// <item><see cref="PixelFormat.Format64bppArgb">Format64bppArgb</see> to
/// <see cref="PixelFormat.Format32bppArgb">Format32bppArgb</see>;</item>
/// <item><see cref="PixelFormat.Format64bppPArgb">Format64bppPArgb</see> to
/// <see cref="PixelFormat.Format32bppPArgb">Format32bppPArgb</see>.</item>
/// </list>
/// </para></remarks>
///
/// <exception cref="UnsupportedImageFormatException">Invalid pixel format of the source image.</exception>
///
public static Bitmap Convert16bppTo8bpp(this Bitmap bitmap)
{
Bitmap newImage = null;
int layers = 0;
// get image size
int width = bitmap.Width;
int height = bitmap.Height;
// create new image depending on source image format
switch (bitmap.PixelFormat)
{
case PixelFormat.Format16bppGrayScale:
// create new grayscale image
newImage = CreateGrayscaleImage(width, height);
layers = 1;
break;
case PixelFormat.Format48bppRgb:
// create new color 24 bpp image
newImage = new Bitmap(width, height, PixelFormat.Format24bppRgb);
layers = 3;
break;
case PixelFormat.Format64bppArgb:
// create new color 32 bpp image
newImage = new Bitmap(width, height, PixelFormat.Format32bppArgb);
layers = 4;
break;
case PixelFormat.Format64bppPArgb:
// create new color 32 bpp image
newImage = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
layers = 4;
break;
default:
throw new UnsupportedImageFormatException("Invalid pixel format of the source image.");
}
// lock both images
BitmapData sourceData = bitmap.LockBits(ImageLockMode.ReadOnly);
BitmapData newData = newImage.LockBits(ImageLockMode.ReadWrite);
unsafe
{
// base pointers
byte* src = (byte*)sourceData.Scan0.ToPointer();
byte* dst = (byte*)newData.Scan0.ToPointer();
// image strides
int sourceStride = sourceData.Stride;
int newStride = newData.Stride;
for (int y = 0; y < height; y++)
{
ushort* s = (ushort*)(src + y * sourceStride);
byte* d = (byte*)(dst + y * newStride);
for (int x = 0, lineSize = width * layers; x < lineSize; x++, s++, d++)
*d = (byte)(*s >> 8);
}
}
// unlock both image
bitmap.UnlockBits(sourceData);
newImage.UnlockBits(newData);
return newImage;
}
/// <summary>
/// Load bitmap from URL.
/// </summary>
///
/// <param name="url">URL to load bitmap from.</param>
///
/// <returns>Returns loaded bitmap.</returns>
///
public static Bitmap FromUrl(string url)
{
return FromUrl(url, String.Empty);
}
/// <summary>
/// Load bitmap from URL.
/// </summary>
///
/// <param name="url">URL to load bitmap from.</param>
/// <param name="localPath">The local directory where the file should be stored.</param>
///
/// <returns>Returns loaded bitmap.</returns>
///
public static Bitmap FromUrl(string url, string localPath)
{
string name = System.IO.Path.GetFileName(url);
string downloadedFileName = System.IO.Path.Combine(localPath, name);
if (!File.Exists(downloadedFileName))
{
#if NET35
if (localPath == null || String.IsNullOrEmpty(localPath.Trim()))
#else
if (!String.IsNullOrWhiteSpace(localPath))
#endif
Directory.CreateDirectory(localPath);
Console.WriteLine("Downloading {0}", url);
using (var client = ExtensionMethods.NewWebClient())
client.DownloadFileWithRetry(url, downloadedFileName);
}
return FromFile(downloadedFileName);
}
/// <summary>
/// Convert bitmap with 8 bits per plane to a bitmap with 16 bits per plane.
/// </summary>
///
/// <param name="bitmap">Source image to convert.</param>
///
/// <returns>Returns new image which is a copy of the source image but with 16 bits per plane.</returns>
///
/// <remarks><para>The routine does the next pixel format conversions:
/// <list type="bullet">
/// <item><see cref="PixelFormat.Format8bppIndexed">Format8bppIndexed</see> (grayscale palette assumed) to
/// <see cref="PixelFormat.Format16bppGrayScale">Format16bppGrayScale</see>;</item>
/// <item><see cref="PixelFormat.Format24bppRgb">Format24bppRgb</see> to
/// <see cref="PixelFormat.Format48bppRgb">Format48bppRgb</see>;</item>
/// <item><see cref="PixelFormat.Format32bppArgb">Format32bppArgb</see> to
/// <see cref="PixelFormat.Format64bppArgb">Format64bppArgb</see>;</item>
/// <item><see cref="PixelFormat.Format32bppPArgb">Format32bppPArgb</see> to
/// <see cref="PixelFormat.Format64bppPArgb">Format64bppPArgb</see>.</item>
/// </list>
/// </para></remarks>
///
/// <exception cref="UnsupportedImageFormatException">Invalid pixel format of the source image.</exception>
///
public static Bitmap Convert8bppTo16bpp(this Bitmap bitmap)
{
Bitmap newImage = null;
int layers = 0;
// get image size
int width = bitmap.Width;
int height = bitmap.Height;
// create new image depending on source image format
switch (bitmap.PixelFormat)
{
case PixelFormat.Format8bppIndexed:
// create new grayscale image
newImage = new Bitmap(width, height, PixelFormat.Format16bppGrayScale);
layers = 1;
break;
case PixelFormat.Format24bppRgb:
// create new color 48 bpp image
newImage = new Bitmap(width, height, PixelFormat.Format48bppRgb);
layers = 3;
break;
case PixelFormat.Format32bppArgb:
// create new color 64 bpp image
newImage = new Bitmap(width, height, PixelFormat.Format64bppArgb);
layers = 4;
break;
case PixelFormat.Format32bppPArgb:
// create new color 64 bpp image
newImage = new Bitmap(width, height, PixelFormat.Format64bppPArgb);
layers = 4;
break;
default:
throw new UnsupportedImageFormatException("Invalid pixel format of the source image.");
}
// lock both images
BitmapData sourceData = bitmap.LockBits(ImageLockMode.ReadOnly);
BitmapData newData = newImage.LockBits(ImageLockMode.ReadWrite);
unsafe
{
// base pointers
byte* src = (byte*)sourceData.Scan0.ToPointer();
byte* dst = (byte*)newData.Scan0.ToPointer();
// image strides
int sourceStride = sourceData.Stride;
int newStride = newData.Stride;
for (int y = 0; y < height; y++)
{
byte* s = (byte*)(src + y * sourceStride);
ushort* d = (ushort*)(dst + y * newStride);
for (int x = 0, lineSize = width * layers; x < lineSize; x++, s++, d++)
*d = (ushort)(*s << 8);
}
}
// unlock both image
bitmap.UnlockBits(sourceData);
newImage.UnlockBits(newData);
return newImage;
}
/// <summary>
/// Gets the color depth used in an image, in number of bytes per pixel.
/// </summary>
/// <param name="image">The image.</param>
public static int GetPixelFormatSizeInBytes(this Bitmap image)
{
return System.Drawing.Image.GetPixelFormatSize(image.PixelFormat) / 8;
}
/// <summary>
/// Gets the color depth used in an image, in number of bits per pixel.
/// </summary>
/// <param name="image">The image.</param>
public static int GetPixelFormatSize(this Bitmap image)
{
return System.Drawing.Image.GetPixelFormatSize(image.PixelFormat);
}
/// <summary>
/// Gets the color depth used in an image, in number of bytes per pixel.
/// </summary>
/// <param name="image">The image.</param>
public static int GetPixelFormatSizeInBytes(this UnmanagedImage image)
{
return System.Drawing.Image.GetPixelFormatSize(image.PixelFormat) / 8;
}
/// <summary>
/// Gets the color depth used in an image, in number of bits per pixel.
/// </summary>
/// <param name="image">The image.</param>
public static int GetPixelFormatSize(this UnmanagedImage image)
{
return System.Drawing.Image.GetPixelFormatSize(image.PixelFormat);
}
}
}