How to change the quality of jpeg images using GDI+

June 08, 2011 - 13:37

Sometimes the standard functions for converting images to jpeg's isn't of a high enough quality. Perhaps you are converting map images or high resolution text documents, where the jpeg artifacts are easily seen.

This example demonstrates how to change this default encoding quality.

<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2d" %>
<%@ import Namespace="System.Runtime.InteropServices" %>

<script runat="server">
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

Dim myimage As New Bitmap(200, 200)
Dim gr As Graphics = Graphics.FromImage(myimage)
gr.DrawLine(Pens.Red, 0, 0, 50, 50)

Dim compression As Long = 130 '# lower value is poor quality, high is better.
Dim myImageCodecInfo As System.Drawing.Imaging.ImageCodecInfo
Dim myEncoder As System.Drawing.Imaging.Encoder
Dim myEncoderParameter As System.Drawing.Imaging.EncoderParameter
Dim myEncoderParameters As System.Drawing.Imaging.EncoderParameters
myImageCodecInfo = GetEncoderInfo("image/jpeg")
myEncoder = System.Drawing.Imaging.Encoder.Quality
myEncoderParameters = New System.Drawing.Imaging.EncoderParameters(1)
myEncoderParameter = New System.Drawing.Imaging.EncoderParameter(myEncoder,compression)
myEncoderParameters.Param(0) = myEncoderParameter

response.contenttype="image/jpeg", myImageCodecInfo,myEncoderParameters)

If you save the above code as is into a .aspx file and execute this you will see a black square with a red line.

To adjust the quality/size of the image alter the compression variable. The lower this value is the lower the quality and smaller size, A higher value the quality is better but the image size is increased.

© 2011