Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2008-12-13
This is what I want to do: Load an image, find the JPEG codec, and use that to re-save the image. In Visual Basic 8, the code might look like this:
Dim MyPics As String = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
Dim B As New System.Drawing.Bitmap(MyPics & “\duck.jpg”)
Dim Codecs() As Imaging.ImageCodecInfo = Imaging.ImageCodecInfo.GetImageEncoders()
For Each Codec As Imaging.ImageCodecInfo In Codecs
If Codec.MimeType = “image/jpeg” Then
‘Create the desiered parameters in a list
Dim HighCompression As New Imaging.EncoderParameter(Imaging.Encoder.Quality, 0)
Dim AllMyParameters As New Imaging.EncoderParameters(1)
AllMyParameters.Param(0) = HighCompression
‘Save the image using the codec and the parameter(s)
B.Save(MyPics & “\high_compression.jpg”, Codec, AllMyParameters)
Exit For
End If
Next
The iteration can be replaced with a Linq expression that simply selects the desired codec. Here, I use a Linq expression to pick the JPEG codec from the list returned from the ImageCodecInfo.GetImageEncoders() function:
Dim Codec As Imaging.ImageCodecInfo = _
(From X In Imaging.ImageCodecInfo.GetImageEncoders() _
Select X Where X.MimeType = “image/jpeg”).First()
So, the complete code that benefits from the new Linq feature looks like this:
‘Load the image I want to re-save
Dim MyPics As String = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
Dim B As New System.Drawing.Bitmap(MyPics & “\duck.jpg”)
‘Use Linq to locate the right codec
Dim Codec As Imaging.ImageCodecInfo = _
(From X In Imaging.ImageCodecInfo.GetImageEncoders() _
Select X Where X.MimeType = “image/jpeg”).First()
‘Create the desiered parameters in a list
Dim HighCompression As New Imaging.EncoderParameter(Imaging.Encoder.Quality, 0)
Dim AllMyParameters As New Imaging.EncoderParameters(1)
AllMyParameters.Param(0) = HighCompression
‘Save the image using the codec and the parameter(s)
B.Save(MyPics & “\high_compression.jpg”, Codec, AllMyParameters)
This is a good example where Linq actually is useful to make the code shorter and more readable.
Categories: Visual Basic 9
Tags: Linq
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply