我创建了一个Web服务,用于从第三方接收图像,然后将其导入到SQL表中。
之后,我检索图像并将其保存到目录中。我最终的Azure数据库。
一切正常,我没有收到任何错误,除非我将图像检索到“测试”图片框中,我得到图像的“红色X”,表示图像有错误。
是否有人能够查看我的代码,看看我做错了什么?这是我第一次做这种事情。
网络服务:
Public Function Wunelli_SendImage(ByVal PolicyRef As String, ByVal ImagePath As String) Implements FreshCloud.Wunelli_SendImage
Using cn As New SqlConnection(sqlConn)
'SqlConnection.ClearAllPools()
Using cmd As New SqlCommand("INSERT INTO [dbo].[Autosaint_Wunelli_Engineer_Images] VALUES(@policyref,GETDATE(),@photo)", cn)
Try
With cmd
.Parameters.AddWithValue("@policyref", "LYJX01PC01")
Using MS As New MemoryStream(), BM As New Bitmap(ImagePath)
BM.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim data As Byte() = MS.GetBuffer()
Dim p As New SqlParameter("@photo", SqlDbType.Image)
p.Value = data
.Parameters.Add(p)
End Using
.Connection.Open()
Return cmd.ExecuteNonQuery()
.Connection.Close()
End With
Catch ex As Exception
MsgBox(ex.Message & " " & ex.StackTrace)
End Try
End Using
End Using
End Function
用于检索图像的WPF测试工具:
Try
Using cn As New SqlConnection(sqlConn)
'SqlConnection.ClearAllPools()
Using cmd As New SqlCommand("SELECT [Image] From [dbo].[Autosaint_Wunelli_Engineer_Images] WHERE [PolicyRef] = 'LYJX01PC01'", cn)
Try
With cmd
.Connection.Open()
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
End If
.Connection.Close()
End With
Catch ex As Exception
MsgBox(ex.Message & " " & ex.StackTrace)
End Try
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message & " " & ex.StackTrace)
End Try
答案 0 :(得分:1)
您必须在图像的生命周期内保持流打开。
所以,改变一下:
Using ms As New MemoryStream(imageData, 0, imageData.Length)
到
Dim ms As New MemoryStream(imageData, 0, imageData.Length)
并删除End Using
,以便不处理该流,并且它应该可以正常工作。
答案 1 :(得分:0)
关于Wunelli_SendImage
方法:
Parameters.AddWithValue
。相反,请显式创建参数并为其指定数据类型,就像使用@photo
。IMAGE
在此应用程序代码中使用,请不要使用SqlDbType.Image
数据类型。相反,请在数据库中使用VARBINARY(MAX)
,然后使用SqlParameter("@photo", SqlDbType.VarBinary, -1)
,其中-1
等同于MAX
。MemoryStream
或Bitmap
个对象。相反,使用p.Value = File.ReadAllBytes(ImagePath)
而不是浪费内存,或者至少摆脱一些不必要的步骤。INSERT
语句应包含字段名称:INSERT INTO [dbo].[Autosaint_Wunelli_Engineer_Images] ([PolicyRef], [Date], [Image]) VALUES (@policyref, GETDATE(), @photo);