温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#如何实现把图片转换成二进制以及把二进制转换成图片

发布时间:2021-05-17 10:49:47 来源:亿速云 阅读:569 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关C#如何实现把图片转换成二进制以及把二进制转换成图片,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

具体如下:

private void button1_Click(object sender, EventArgs e)
{
 string path = this.textBox1.Text;
 byte[] imgBytesIn = SaveImage(path);
 ShowImgByByte(imgBytesIn);
 //Parameters.Add("@Photo", SqlDbType.Binary).Value = imgBytesIn;
}
//将图片以二进制流
public byte[] SaveImage(String path)
{
 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
 BinaryReader br = new BinaryReader(fs);
 byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
 return imgBytesIn;
}
//现实二进制流代表的图片
public void ShowImgByByte(byte[] imgBytesIn)
{
 MemoryStream ms = new MemoryStream(imgBytesIn);
 pictureBox1.Image = Image.FromStream(ms);
}

二、将图片保存到数据库中,并从数据库中读取:

#region 将图片从数据库中读取
/// <summary>
/// 将图片从数据库中读取
/// </summary>
/// <param name="xs_ID">要读取图片的学号</param>
/// <param name="ph">pictureBox1控件名</param>
public void get_photo(string xs_ID, PictureBox ph)//将图片从数据库中读取
{
 byte[] imagebytes = null;
 getcon();
 SqlCommand con = new SqlCommand("select * from S_jiben where S_num='" + xs_ID + "'", link);
 SqlDataReader dr = con.ExecuteReader();
 while (dr.Read())
 {
  imagebytes =(byte[])dr.GetValue(18);
 }
 dr.Close();
 con_close();
 MemoryStream ms = new MemoryStream(imagebytes);
 Bitmap bmpt = new Bitmap(ms);
 ph.Image = bmpt;
}
#endregion
#region
public void SaveImage(string MID, OpenFileDialog openF)//将图片以二进制存入数据库中
{
 string strimg = openF.FileName.ToString(); //记录图片的所在路径
 FileStream fs = new FileStream(strimg, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
 BinaryReader br = new BinaryReader(fs);
 byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
 getcon();
 StringBuilder strSql = new StringBuilder();
 strSql.Append("update S_jiben Set xs_photo=@Photo where S_num=" + MID);
 SqlCommand cmd = new SqlCommand(strSql.ToString(), link);
 cmd.Parameters.Add("@Photo", SqlDbType.Binary).Value = imgBytesIn;
 cmd.ExecuteNonQuery();
 con_close();
}
#endregion

C#是什么

C#是一个简单、通用、面向对象的编程语言,它由微软Microsoft开发,继承了C和C++强大功能,并且去掉了一些它们的复杂特性,C#综合了VB简单的可视化操作和C++的高运行效率,以其强大的操作能力、优雅的语法风格、创新的语言特性和便捷的面向组件编程从而成为.NET开发的首选语言,但它不适用于编写时间急迫或性能非常高的代码,因为C#缺乏性能极高的应用程序所需要的关键功能。

关于“C#如何实现把图片转换成二进制以及把二进制转换成图片”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI