如何使用VB.Net/C#从SQL数据库导出图像到特定文件夹

本文关键字:图像 文件夹 数据库 SQL VB 何使用 Net | 更新日期: 2023-09-27 17:53:25

我有这个SQL数据库"学生",我想从它的表"StudentPic"导出图像(全部或选定)到一个特定的文件夹与".jpg"扩展名。

这是我的工作,它没有工作。对此有何评论?

Dim sql As String = " SELECT TOP 10 StudID,StudentPic FROM Student"
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
conn.Open
Dim dr As SqlDataReader = cmd.ExecuteReader
While dr.Read
    Dim bytes() As Byte = CType(dr("StudentPic"),Byte())
    Dim memStream As MemoryStream = New MemoryStream(bytes)
    Try 
        Dim MyImage As Bitmap = New Bitmap(memStream)
        MyImage = New Bitmap(MyImage, 200, 250)
        MyImage.Save((dr("StudID") + ".jpg"), ImageFormat.Jpeg)
    Catch ex As Exception
        Throw ex
    End Try
End While

如何使用VB.Net/C#从SQL数据库导出图像到特定文件夹

您可以使用查询从表中选择图像,然后使用.net image函数将图像保存到磁盘。这并不太难,但正如已经提到的,期望在这里编写代码并不是一个好主意。我会在。net中深入研究它,如果你被卡住了,然后在这里发布你的问题(详细信息)。好运!

您可以将图像检索到字节数组中,然后使用FileStream写入文件。示例:

从数据库中检索图像与将图像保存到数据库的过程完全相反。

SqlCommand cmd = new SqlCommand("select Pic from StudentPic where StudentID=@ID", 
                   new SqlConnection("conn stirng"));cmd.Parameters.AddWithValue("@ID",'id of a student');cmd.Connection.Open();

执行" ExecuteScalar ",因为我们只想要返回" IMAGE "列的数据。

byte[] byteImg=(byte[])cmd.ExecuteScalar();cmd.Connection.Close();

将此数据保存到文件夹

string strPath=Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "''StudentPics''"+"picName.jpg";
    FileStream fs=new FileStream(strFileTime,FileMode.CreateNew,FileAccess.Write);
    fs.Write(byteImg,0,byteImg.Length);fs.Flush();fs.Close();

希望能帮上忙。