PictureBox从文件到BLOB到SQL Server数据库,然后从DB到PictureBox

时间:2012-07-14 23:30:39

标签: c# winforms linq-to-sql blob picturebox

我有一个带有1个pictureBox,1个textBox和3个按钮的Windows窗体:LoadFromFile,SaveToDB和LoadFromDB。

在App.config中使用LINQ to SQL连接,并在表单中使用下一个代码:

private void btnLoadFromFile_Click(object sender, EventArgs e)
{
// open file dialog
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png";
if (open.ShowDialog() == DialogResult.OK)
{
// display image in picture box
picBox.Image = new Bitmap(open.FileName);
// image file path
textBox1.Text = open.FileName;
}
}

我可以加载Picture及其形成路径。

现在我需要将图片保存到表格中[BLOBData]的图像类型字段:tblBLOB (BLOBID, BLOBData)。那么将图片转换为图片类型的代码是什么,然后将图像类型转换为图片以在PictureBox控件中显示它的代码是什么?

1 个答案:

答案 0 :(得分:2)

Byte Array存储为DataBase中的blob。一些有用的转换方法:

public static byte[] ImageToByteArray(Image imageIn)
{
    var ms = new MemoryStream();
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public static Image ByteArrayToImage(byte[] byteArrayIn)
{
    var ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

存储到DB:

OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == DialogResult.OK)
{
    // display image in picture box
    Image img = new Bitmap(open.FileName);
    picBox.Image = img;
    // Byte Array that can store as BLOB in DB
    byte[] blobData = ImageToByteArray(img);
}

并从DB加载:

picBox.Image = ByteArrayToImage(/* Byte Array of image from BLOB cell in DB */);