一,图片转base64字符串
//图片转base64字符串方法
public static string ImageEncodeToBase64(Image image)
{
System.IO.MemoryStream m = new System.IO.MemoryStream();//实例化内存流.因为MemoryStream前面加了System.IO.所以不用在最上方添加引用using System.IO
image.Save(m, System.Drawing.Imaging.ImageFormat.Gif);//将图片存入内存流
string base64string = Convert.ToBase64String(m.GetBuffer());//将内存流中的数据转换为base64字符串,Convert方法
return base64string;//返回字符串
}
二,base64字符串转图片
//base64字符串转图片方法
public static Image Base64DecodeToImage(string base64string)
{//使用trycatch语句抓取错误
try
{
byte[] bt = Convert.FromBase64String(base64string);//尝试把字符串存入二进制数组,Convert方法
System.IO.MemoryStream stream = new System.IO.MemoryStream(bt);//将二进制数组存入内存流
return Image.FromStream(stream);//返回Image类型数据
}
catch
{
return null;//抓取错误后的处理方法
}
}
三,带界面的转换示例程序
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练习1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Bitmap bit1;//上提示图片(图片1)
//private Bitmap bit2;//验证码图片(图片2)
//图片转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字符串转图片方法
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("请输入base64字符串");
}
else
{
pictureBox2.Image = Base64DecodeToImage(textBox1.Text);
}
}
}
}