Base64Util.cs
1.4 KB
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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace AOI
{
public class Base64Util
{
/// <summary>
/// 将图片数据转换为Base64字符串
/// </summary>
public static string ToBase64(Image img)
{
if (img == null)
{
return "";
}
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(memStream, img);
byte[] bytes = memStream.GetBuffer();
string base64 = Convert.ToBase64String(bytes);
return base64;
}
}
/// <summary>
/// 将Base64字符串转换为图片
/// </summary>
public static Image ToImage(string base64)
{
if (base64 == null || base64 == "")
{
return null;
}
byte[] bytes = Convert.FromBase64String(base64);
using (MemoryStream memStream = new MemoryStream(bytes))
{
BinaryFormatter binFormatter = new BinaryFormatter();
Image img = (Image)binFormatter.Deserialize(memStream);
return img;
}
}
}
}