-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitmapManager.cs
83 lines (74 loc) · 2.65 KB
/
BitmapManager.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
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;
namespace Common
{
public static class BitmapManager
{
public static BitmapSource BitmapToBitmapSource(Bitmap source)
{
using (MemoryStream memory = new MemoryStream())
{
source.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}
public static Bitmap BitmapSourceToBitmap(BitmapSource source)
{
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(source));
enc.Save(outStream);
Bitmap bitmap = new Bitmap(outStream);
// return bitmap; <-- leads to problems, stream is closed/closing ...
return new Bitmap(bitmap);
}
}
public static void BitmapSourceToFile(BitmapSource image, string filePath)
{
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(fileStream);
}
}
private static ImageFormat encodingFormat = ImageFormat.Png;
public static byte[] BitmapToBytes(Bitmap bmp, string encoding = "")
{
encoding = encoding.ToLower();
switch (encoding)
{
case "gif":
encodingFormat = ImageFormat.Gif;
break;
case "png":
encodingFormat = ImageFormat.Png;
break;
case "jpeg":
encodingFormat = ImageFormat.Jpeg;
break;
case "tiff":
encodingFormat = ImageFormat.Tiff;
break;
default:
throw new System.Exception($"Unrecognized image encoding: {encoding}");
}
byte[] bytes = null;
using (var stream = new MemoryStream())
{
bmp.Save(stream, encodingFormat);
bytes = stream.ToArray();
}
return bytes;
}
}
}