一,圖片轉(zhuǎn)base64字符串
//圖片轉(zhuǎn)base64字符串方法
public static string ImageEncodeToBase64(Image image)
{
System.IO.MemoryStream m = new System.IO.MemoryStream();//實(shí)例化內(nèi)存流.因?yàn)镸emoryStream前面加了System.IO.所以不用在最上方添加引用using System.IO
image.Save(m, System.Drawing.Imaging.ImageFormat.Gif);//將圖片存入內(nèi)存流
string base64string = Convert.ToBase64String(m.GetBuffer());//將內(nèi)存流中的數(shù)據(jù)轉(zhuǎn)換為base64字符串,Convert方法
return base64string;//返回字符串
}
二,base64字符串轉(zhuǎn)圖片
//base64字符串轉(zhuǎn)圖片方法
public static Image Base64DecodeToImage(string base64string)
{//使用trycatch語(yǔ)句抓取錯(cuò)誤
try
{
byte[] bt = Convert.FromBase64String(base64string);//嘗試把字符串存入二進(jìn)制數(shù)組,Convert方法
System.IO.MemoryStream stream = new System.IO.MemoryStream(bt);//將二進(jìn)制數(shù)組存入內(nèi)存流
return Image.FromStream(stream);//返回Image類型數(shù)據(jù)
}
catch
{
return null;//抓取錯(cuò)誤后的處理方法
}
}
三,帶界面的轉(zhuǎn)換示例程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WFA練習(xí)1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Bitmap bit1;//上提示圖片(圖片1)
//private Bitmap bit2;//驗(yàn)證碼圖片(圖片2)
//圖片轉(zhuǎn)base64字符串方法
public static string ImageEncodeToBase64(Image image)
{
System.IO.MemoryStream m = new System.IO.MemoryStream();
image.Save(m, System.Drawing.Imaging.ImageFormat.Gif);
string base64string = Convert.ToBase64String(m.GetBuffer());
return base64string;
}
//base64字符串轉(zhuǎn)圖片方法
public static Image Base64DecodeToImage(string base64string)
{
try
{
byte[] bt = Convert.FromBase64String(base64string);
System.IO.MemoryStream stream = new System.IO.MemoryStream(bt);
return Image.FromStream(stream);
}
catch
{
return null;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
string path = this.openFileDialog1.FileName;//獲得圖片路徑
bit1 = new Bitmap(path);
this.pictureBox1.Image = bit1;
textBox1.Text = ImageEncodeToBase64(pictureBox1.Image);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text=="")
{
MessageBox.Show("請(qǐng)輸入base64字符串");
}
else
{
pictureBox2.Image = Base64DecodeToImage(textBox1.Text);
}
}
}
}