2017-08-11 107 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

谢谢你的建议 –