|
|
Title | Save JPEG files with different levels of compression in VB .NET |
Keywords | JPEG, compress, compression, optimization |
Categories | Graphics, VB.NET |
|
|
Thanks to Neil Crosby.
When the user changes the selected compression level, the program saves an image with the desired compression. It then displays the file's size and displays the file so you can see the effect of the compression. This lets you easily judge the tradeoff between compression and image quality.
|
|
Private Sub cbCI_SelectedIndexChanged(ByVal sender As _
Object, ByVal e As System.EventArgs) Handles _
cbCI.SelectedIndexChanged
'Release loaded file
If Not (pbPic.Image Is Nothing) Then
pbPic.Image.Dispose()
pbPic.Image = Nothing
End If
pbPic.Image = Image.FromFile(Application.StartupPath & _
"\temp100.jpg")
SaveJPGWithCompressionSetting(pbPic.Image, _
Application.StartupPath & "\temp.jpg", _
Val(cbCI.Text))
pbPic.Image = Image.FromFile(Application.StartupPath & _
"\temp.jpg")
lblCI.Text = cbCI.Text
Dim FileSize As Long
Dim suffit As String
FileSize = FileLen(Application.StartupPath & _
"\temp.jpg")
If FileSize < 1000 Then
suffit = " Bytes"
GoTo showit
End If
If FileSize > 1000000 Then
FileSize = Int(FileSize / 1000000)
suffit = " Mb"
GoTo showit
Else
FileSize = Int(FileSize / 1000)
suffit = " Kb"
End If
showit: lblTemp.Text = FileSize & suffit
End Sub
Private Sub SaveJPGWithCompressionSetting(ByVal image As _
Image, ByVal szFileName As String, ByVal lCompression _
As Long)
Dim eps As EncoderParameters = New EncoderParameters(1)
eps.Param(0) = New EncoderParameter(Encoder.Quality, _
lCompression)
Dim ici As ImageCodecInfo = GetEncoderInfo("image/jpeg")
image.Save(szFileName, ici, eps)
End Sub
Private Function GetEncoderInfo(ByVal mimeType As String) _
As ImageCodecInfo
Dim j As Integer
Dim encoders As ImageCodecInfo()
encoders = ImageCodecInfo.GetImageEncoders()
For j = 0 To encoders.Length
If encoders(j).MimeType = mimeType Then
Return encoders(j)
End If
Next j
Return Nothing
End Function
|
|
|
|
|
|