在将图像插入数据库之前压缩图像

时间:2017-08-11 13:47:50

标签: vb.net winforms

我在数据库中的表(SQL server)包含image列,如何在将图像插入数据库之前压缩图像? 或者如果我需要做任何解决方案,我将很高兴,这就是我需要的: 我正在为租赁商店制作一个小程序,因此用户将打印合同,并且在打印并签署合同后,用户想要再次存储它,以便他可以随时检索它。我正在使用图像列来允许用户将合同副本作为图像,但问题是合同是2页,因此对于一个合同我需要2个图像,这需要大量空间。 有什么方法可以延期。我正在使用服务器为连接到该程序的所有计算机提供信息。

这是插入图片的代码:

Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
    Dim fName As String
    fName = imagepath
    If File.Exists(fName) Then

        Dim content As Byte() = ImageToStream(fName)
        'فحص الاتصال بقاعدة البيانات
        If SQL.conn.State = ConnectionState.Open Then
            SQL.conn.Close()
        End If
        SQL.conn.Open()


        Dim cmd As New SqlCommand()
        cmd.CommandText = "insert into test (image) values(@image)"
        cmd.Parameters.AddWithValue("@image", (content))


        cmd.Connection = SQL.conn
        cmd.ExecuteNonQuery()
        SQL.conn.Close()
    Else
        MsgBox(fName & " الصورة المختارة ليست موجودة او غير صالحة  ", vbCritical, "حصل خطأ")
    End If
End Sub

Dim imagepath As String
Dim myStream As IO.Stream = Nothing
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim openFileDialog1 As New OpenFileDialog()
    'Set the Filter.
    openFileDialog1.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png"
    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        Try
            myStream = openFileDialog1.OpenFile()
            If (myStream IsNot Nothing) Then
                imagepath = openFileDialog1.FileName

            End If
        Catch Ex As Exception
            MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
        Finally
            ' Check this again, since we need to make sure we didn't throw an exception on open.
            If (myStream IsNot Nothing) Then
                myStream.Close()
            End If
        End Try
    Else
        openFileDialog1.FileName = Nothing
        Return
    End If
End Sub
Private Function ImageToStream(ByVal fileName As String) As Byte()
    Dim stream As New MemoryStream()
tryagain:
    Try
        Dim image As New Bitmap(fileName)
        image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
    Catch ex As Exception
        GoTo tryagain
    End Try

    Return stream.ToArray()
End Function

1 个答案:

答案 0 :(得分:0)

我不建议压缩图像。不幸的是,这可能对许多更常见的图像格式(例如Jpeg)影响不大,因为它们已经被压缩了。

您可以在上传图像时将质量调整到最小(同时仍然是可读图像)。但我建议在扫描它们的时候这样做。这样每个人都可以看到它仍然可读。