2017-08-11 155 views
0

我在數據庫(SQL服務器)的表中包含圖像列,如何在將圖像插入數據庫之前壓縮圖像? 或者如果有什麼解決方案,我需要做什麼我會很高興,這是我需要的: 我正在做一個租賃商店的小程序,所以用戶將打印合同,並在合同打印並簽署了用戶想要的再次存儲它,以便他可以隨時找回它。我使用圖像列允許用戶有合同副本作爲圖像,但問題是,合同是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 

回答

0

我不會建議壓縮圖像。不幸的是,這可能對很多更常見的圖像格式(如Jpeg)影響很小,因爲它們已經被壓縮了。

您可以在圖像上傳時將質量調整到最小(同時仍是可讀圖像)。但我建議在掃描時進行此操作。這樣每個人都可以看到它仍然可讀。

+0

謝謝你的建議 –