Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Using Linq to locate a codec

2008-12-13

In a previous post, I mentioned that Linq could be used to locate the desired codec when you’re saving an image. Instead of iterating through the codecs, and halt when the right one shows up, I could just select the desired one. 

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

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips