forked from topnguyen/Elect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageHelper.cs
425 lines (340 loc) · 13.7 KB
/
ImageHelper.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
#region License
//--------------------------------------------------
// <License>
// <Copyright> 2018 © Top Nguyen </Copyright>
// <Url> http://topnguyen.com/ </Url>
// <Author> Top </Author>
// <Project> Elect </Project>
// <File>
// <Name> ImageHelper.cs </Name>
// <Created> 04/04/2018 5:31:08 PM </Created>
// <Key> e727ea18-5493-45a9-93bd-f225825a7cda </Key>
// </File>
// <Summary>
// ImageHelper.cs is a part of Elect
// </Summary>
// <License>
//--------------------------------------------------
#endregion License
using Elect.Core.CheckUtils;
using Elect.Data.IO.FileUtils;
using Elect.Data.IO.ImageUtils.ColorUtils;
using Elect.Data.IO.ImageUtils.Models;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using Elect.Core.ByteUtils;
namespace Elect.Data.IO.ImageUtils
{
public class ImageHelper
{
#region Image Info
/// <summary>
/// <para> Get image info. </para>
/// <para> If not know mime type but valid image then return <see cref="ImageConstants.ImageMimeTypeUnknown" /> </para>
/// <para> Invalid image will be return <c> NULL </c> </para>
/// </summary>
/// <param name="base64"></param>
public static ImageModel GetImageInfo(string base64)
{
byte[] bytes = Convert.FromBase64String(base64);
return GetImageInfo(bytes);
}
/// <summary>
/// <para> Get image info. </para>
/// <para> If not know mime type but valid image then return <see cref="ImageConstants.ImageMimeTypeUnknown" /> </para>
/// <para> Invalid image will be return <c> NULL </c> </para>
/// </summary>
/// <param name="bytes"></param>
public static ImageModel GetImageInfo(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
return GetImageInfo(stream);
}
}
/// <summary>
/// <para> Get image info. </para>
/// <para> If not know mime type but valid image then return <see cref="ImageConstants.ImageMimeTypeUnknown" /> </para>
/// <para> Invalid image will be return <c> NULL </c> </para>
/// </summary>
/// <param name="imageStream"></param>
public static ImageModel GetImageInfo(MemoryStream imageStream)
{
try
{
ImageModel imageModel = new ImageModel();
// Check Vector image first, if image is vector then no info for width and height
if (IsSvgImage(imageStream))
{
imageModel.MimeType = "image/svg+xml";
}
else
{
// Raster check (jpg, png, etc.)
using (var image = Image.FromStream(imageStream))
{
// Get image mime type
bool isUnknownMimeType = true;
foreach (var imageCodecInfo in ImageCodecInfo.GetImageDecoders())
{
if (imageCodecInfo.FormatID == image.RawFormat.Guid)
{
imageModel.MimeType = imageCodecInfo.MimeType;
isUnknownMimeType = false;
break;
}
}
if (isUnknownMimeType)
{
imageModel.MimeType = ImageConstants.ImageMimeTypeUnknown;
}
// Get width and height in pixel info
imageModel.WidthPx = image.Width;
imageModel.HeightPx = image.Height;
}
}
// Get others info
imageModel.Extension = MimeTypeHelper.GetExtension(imageModel.MimeType);
// Get image dominant color
using (var bitmap = new Bitmap(imageStream))
{
imageModel.DominantHexColor = ImageDominantColorHelper.GetHexCode(bitmap);
}
return imageModel;
}
catch
{
return null;
}
}
public static bool IsSvgImage(MemoryStream imageStream)
{
try
{
imageStream.Position = 0;
byte[] bytes = imageStream.ToArray();
var text = Encoding.UTF8.GetString(bytes);
bool isSvgImage = text.StartsWith("<?xml ") || text.StartsWith("<svg ");
return isSvgImage;
}
catch
{
return false;
}
}
#endregion
#region Text Image
/// <summary>
/// Generate image from text (at center of the image)
/// </summary>
/// <param name="text"> Will be StringHelper.Normalize(text).First().ToString() </param>
/// <param name="width"> Default is 50 px </param>
/// <param name="height"> Default is 50 px </param>
/// <param name="textColor"> Default is random color </param>
/// <param name="backgroundColor"> Default is random color </param>
/// <param name="font">
/// Default is new Font(FontFamily.GenericSansSerif, 10.0F, FontStyle.Bold)
/// </param>
/// <returns></returns>
public static string GenerateTextImageBase64(string text, int width = 50, int height = 50, Color textColor = default, Color backgroundColor = default, Font font = null)
{
if (font == null)
{
font = new Font(FontFamily.GenericSansSerif, 10.0F, FontStyle.Bold);
}
if (textColor == default)
{
textColor = ColorHelper.GetRandom();
}
if (backgroundColor == default)
{
backgroundColor = ColorHelper.GetRandom();
}
// Generate Image
var img = GenerateTextImage(text, width, height, textColor, backgroundColor, font);
// Convert to image array
using (MemoryStream memoryStream = new MemoryStream())
{
img.Save(memoryStream, img.RawFormat);
var imageArray = memoryStream.ToArray();
if (!imageArray.Any())
{
return null;
}
var stringBase64 = Convert.ToBase64String(imageArray);
return stringBase64;
}
}
/// <summary>
/// Generate image from text (at center of the image)
/// </summary>
/// <param name="text"> </param>
/// <param name="width"> </param>
/// <param name="height"> </param>
/// <param name="textColor"> </param>
/// <param name="backgroundColor"></param>
/// <param name="font"> </param>
/// <returns></returns>
public static Image GenerateTextImage(string text, int width, int height, Color textColor, Color backgroundColor, Font font)
{
CheckHelper.CheckNullOrWhiteSpace(text, nameof(text));
// Create a dummy bitmap just to get a graphics object
Image img = new Bitmap(1, 1);
Graphics drawing = Graphics.FromImage(img);
// Measure the string to see how big the image needs to be
drawing.MeasureString(text, font);
// Free up the dummy image and old graphics object
img.Dispose();
drawing.Dispose();
// Create a new image of the right size
img = new Bitmap(height, width);
drawing = Graphics.FromImage(img);
// Paint the background
drawing.Clear(backgroundColor);
// Create a brush for the text
Brush brush = new SolidBrush(textColor);
// String alignment
StringFormat stringFormat = new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
};
// Rectangular
RectangleF rectangleF = new RectangleF(0, 0, img.Width, img.Height);
// Draw text on image
drawing.DrawString(text, font, brush, rectangleF, stringFormat);
// Save drawing
drawing.Save();
// Dispose
brush.Dispose();
drawing.Dispose();
// return image
return img;
}
#endregion
#region Base 64
/// <summary>
/// Get image base64 for "src" of "img" element in HTML.
/// </summary>
/// <param name="base64"> </param>
/// <param name="imageExtension"></param>
/// <returns></returns>
public static string GetImageBase64Format(string base64, string imageExtension = ".jpg")
{
var imageMimeType = MimeTypeHelper.GetMimeType(imageExtension);
return $@"data:{imageMimeType};base64,{base64}";
}
/// <summary>
/// Get string base64 data from "src" of "img" element in HTML.
/// </summary>
/// <param name="imageBase64"></param>
/// <returns></returns>
public static string GetBase64Format(string imageBase64)
{
return imageBase64.Split(',').LastOrDefault();
}
#endregion
#region Rotate
/// <summary>
/// Rotate image by Exif Orientation.
/// </summary>
/// <param name="imageBase64"></param>
/// <remarks>This one will fix auto rotate in image uploaded from Mobile Device (iOS, Android and so on).</remarks>
public static string RotateByExifOrientation(string imageBase64)
{
var fileBytes = Convert.FromBase64String(imageBase64);
var fixedAutoRotateFileBytes = RotateByExifOrientation(fileBytes);
return fixedAutoRotateFileBytes.ToBase64();
}
/// <summary>
/// Rotate image by Exif Orientation.
/// </summary>
/// <param name="imageBytes"></param>
/// <remarks>This one will fix auto rotate in image uploaded from Mobile Device (iOS, Android and so on).</remarks>
public static byte[] RotateByExifOrientation(byte[] imageBytes)
{
using (var imageStream = new MemoryStream(imageBytes))
{
var originalImage = Image.FromStream(imageStream);
var fixedAutoRotateImage = RotateByExifOrientation(originalImage);
using (var fixedAutoRotateImageStream = new MemoryStream())
{
fixedAutoRotateImage.Save(fixedAutoRotateImageStream, ImageFormat.Jpeg);
var fixedAutoRotateFileBytes = fixedAutoRotateImageStream.ToArray();
return fixedAutoRotateFileBytes;
}
}
}
/// <summary>
/// Rotate image by Exif Orientation.
/// </summary>
/// <param name="image"></param>
/// <remarks>This one will fix auto rotate in image uploaded from Mobile Device (iOS, Android and so on).</remarks>
public static Image RotateByExifOrientation(Image image)
{
const int orientationId = 0x0112;
var fixedAutoRotateImage = (Image)image.Clone();
if (!fixedAutoRotateImage.PropertyIdList.Contains(orientationId))
{
return fixedAutoRotateImage;
}
int rotationValue = fixedAutoRotateImage.GetPropertyItem(orientationId).Value[0];
var rotateFlipType = RotateFlipType.RotateNoneFlipNone;
switch (rotationValue)
{
case 1: // landscape, do nothing
default:
{
break;
}
case 2:
{
rotateFlipType = RotateFlipType.RotateNoneFlipX;
break;
}
case 3: // bottoms up
{
rotateFlipType = RotateFlipType.Rotate180FlipNone;
break;
}
case 4:
{
rotateFlipType = RotateFlipType.Rotate180FlipX;
break;
}
case 5:
{
rotateFlipType = RotateFlipType.Rotate90FlipX;
break;
}
case 6: // rotated 90 left
{
rotateFlipType = RotateFlipType.Rotate90FlipNone;
break;
}
case 7:
{
rotateFlipType = RotateFlipType.Rotate270FlipX;
break;
}
case 8: // rotated 90 right
{
rotateFlipType =RotateFlipType.Rotate270FlipNone;
break;
}
}
if (rotateFlipType == RotateFlipType.RotateNoneFlipNone)
{
return fixedAutoRotateImage;
}
fixedAutoRotateImage.RotateFlip(rotateFlipType);
fixedAutoRotateImage.RemovePropertyItem(orientationId);
return fixedAutoRotateImage;
}
#endregion
}
}