【发布时间】:2020-07-28 01:47:57
【问题描述】:
我正在尝试将图像保存到列类型设置为图像的 MSSQL 数据库表中,我的应用程序的目的是将用户上传的图像保存到数据库中,以后用户可以从数据库中检索这些图像并如果需要,保存到磁盘。
我已经编写了以下代码以成功完成此任务,但是当我将图像保存到从数据库中检索的磁盘时,文件大小似乎小于原始大小。
这自然意味着图像的质量在保存时降低了,或者我没有正确检索图像。
此代码用于从数据库中检索图像。
Public Function __IMAGE_FROM_STREAM(ByVal img As Object) As Image
__IMAGE_FROM_STREAM = Nothing
If Not IsDBNull(img) Then
Using mStream As New MemoryStream(img, 0, img.Length)
mStream.Write(img, 0, img.Length)
__IMAGE_FROM_STREAM = Image.FromStream(mStream, True)
End Using
End If
Return __IMAGE_FROM_STREAM
End Function
此代码用于将传入的图像保存到数据库中。
Public Function __IMAGE_TO_STREAM(ByVal image As Image) As Byte()
__IMAGE_TO_STREAM = Nothing
If Not image Is Nothing Then
Using mStream As New MemoryStream
Dim bm As Bitmap = New Bitmap(image)
bm.Save(mStream, image.RawFormat)
__IMAGE_TO_STREAM = mStream.GetBuffer
End Using
End If
Return __IMAGE_TO_STREAM
End Function
此代码用于将检索到的图像保存到磁盘中。
sfdExportImage.FileName = "export_" & DateTime.Now.ToString("d").Replace("/", "") & "_" & sender.Tag
If sfdExportImage.ShowDialog() = DialogResult.OK Then
Dim fileName As String = sfdExportImage.FileName
Dim expImage As Image = flpImageContainer.Controls("flpWrap_" & sender.Tag).Controls(0).BackgroundImage
Try
If expImage IsNot Nothing Then
expImage.Save(fileName)
MessageBox.Show("File exported successfully to " & fileName, __COMPANYNAME, MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
__WRITELOG(ex)
End Try
End If
我已经查看了这个问题,但没有类似的问题,我是否遗漏了任何编码参数,我没有使用过很多图像及其类,因此非常感谢您的反馈。谢谢。
【问题讨论】:
-
SQL Server 中的
image数据类型已经过时了十多年,文档会告诉您应该使用varbinary来保存任何二进制数据。 -
我还在使用 MSSQL2008R2 会更新列类型,但这不是问题的原因吧?
-
不,因此是评论而不是回答。
标签: .net vb.net visual-studio-2010