c# 图片 与 BASE64 字符串 互相转换。

时间:2023-01-11 12:19:15
 1 using System;
2 using System.Collections.Generic;
3 using System.Drawing;
4 using System.IO;
5 using System.Linq;
6 using System.Web;
7 using System.Drawing.Imaging;
8 // 博客园 aC#Coder 整理
9 namespace Html5Image.Tools
10 {
11 public class ImageTool
12 {
13 //图片 转为 base64编码的文本
14 public static string ImgToBase64String(Bitmap bmp)
15 {
16 //Bitmap bmp = new Bitmap(Imagefilename);
17 //this.pictureBox1.Image = bmp;
18 //FileStream fs = new FileStream(Imagefilename + ".txt", FileMode.Create);
19 //StreamWriter sw = new StreamWriter(fs);
20
21 MemoryStream ms = new MemoryStream();
22 bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
23 byte[] arr = new byte[ms.Length];
24 ms.Position = 0;
25 ms.Read(arr, 0, (int)ms.Length);
26 ms.Close();
27 String strbaser64 = Convert.ToBase64String(arr);
28
29 return strbaser64;
30 }
31
32 public static Bitmap Base64StringToImage(string base64Img)
33 {
34 byte[] bytes = Convert.FromBase64String(base64Img);
35 MemoryStream ms = new MemoryStream();
36 ms.Write(bytes, 0, bytes.Length);
37 Bitmap bmp = new Bitmap(ms);
38
39 return bmp;
40 }
41
42 /// <summary>
43 /// 保存图片
44 /// </summary>
45 /// <param name="base64Img"></param>
46 /// <param name="imgPath"></param>
47 /// <param name="imgFormat">EX: System.Drawing.Imaging.Jpeg </param>
48 public static void SaveFile(string base64Img, string imgPath, ImageFormat imgFormat )
49 {
50 string dir = Path.GetDirectoryName(imgPath);
51 if (!Directory.Exists(dir))
52 {
53 Directory.CreateDirectory(dir);
54 }
55 var bitmap = Base64StringToImage(base64Img);
56 bitmap.Save(imgPath, imgFormat);
57 }
58 }
59 }