用数据库存储图片乃至文件主要有两种方式,存储byte串和存储文件路径。虽然byte串存多了数据库没准很快会被撑出问题或需要维护,但是数据量比较小时反而容易保证数据安全。
using System;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
public class PicToByte
{
/// <summary>
/// 获得指定图片的二进制数据流
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
static public byte[] GetBinaryPhoto(Image img)
{
MemoryStream stream = new MemoryStream();
img.Save(stream, ImageFormat.Bmp);
BinaryReader br = new BinaryReader(stream);
byte[] photo = stream.ToArray();
stream.Close();
return photo;
}
/// <summary>
/// 找到指定图片文件并获得其二进制数据流
/// </summary>
/// <returns></returns>
static public byte[] GetBinaryPhoto()
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Filter = "图像文件(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|所有文件(*.*)|*.*";
if (openDialog.ShowDialog() != DialogResult.OK)
{
return null;
}
Image img = new Bitmap(openDialog.FileName);
MemoryStream stream = new MemoryStream();
img.Save(stream, ImageFormat.Bmp);
BinaryReader br = new BinaryReader(stream);
byte[] photo = stream.ToArray();
stream.Close();
return photo;
}
/// <summary>
/// 用指定二进制数据流生成图片
/// </summary>
/// <param name="photo"></param>
/// <returns></returns>
static public Image GetGraphicPhoto(byte[] photo)
{
MemoryStream ms = new MemoryStream(photo);
ms.Position = 0;
Image graphicPhoto = Image.FromStream(ms);
ms.Close();
return graphicPhoto;
}
}