C#将照片或图片转化为byte[]存入数据库,从数据库中读照片

本文介绍了如何使用C#实现图片与数据库之间的交互操作,包括将PictureBox中的图片转换为byte[]格式存入数据库、从文件路径读取图片并转为byte[]存储,以及从数据库读取byte[]数据并还原为图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 写入数据库:

public static byte[] GetBytesByImage(PictureBox pb)
{
byte[] photo_byte= null;

if (!pb.Image.Equals(null))
{
using (MemoryStream ms = new MemoryStream())
{
Bitmap bmp
= new Bitmap(pb.Image);
bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
photo_byte
= new byte[ms.Length];
ms.Position
= 0;
ms.Read(photo_byte,
0, Convert.ToInt32(ms.Length));
bmp.Dispose();
}
}

return photo_byte;
}
2.将实际位置中的照片转化为byte[]类型写入数据库中:

public static byte[] GetBytesByImagePath(string strFile)
{
byte[] photo_byte = null;
using (FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
photo_byte
= br.ReadBytes((int)fs.Length);
}
}

return photo_byte;
}
3. 读取byte[]并转化为图片:

public static Image GetImageByBytes(byte[] bytes)
{
Image photo
= null;
using (MemoryStream ms = new MemoryStream(bytes))
{
ms.Write(bytes,
0, bytes.Length);
photo
= Image.FromStream(ms, true);
}

return photo;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值