views:

11672

answers:

7

Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?

+2  A: 

This looks like it has some source code that might help you... I suspect you were just missing the Quality encoder parameter <shrug>

-- Kevin Fairchild

Kevin Fairchild
A: 

You can try:

Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic;

and

Bitmap.CompositingQuality = CompositingQuality.HighQuality;

Which does keep the quality fairly high, but not the highest possible.

GateKiller
A: 

Fundamentally you won't be able to keep the same quality because jpg is (so far as I'm aware) always lossy even with the highest possible quality settings.

If bit-accurate quality is really important, consider using png, which has some modes which are lossless.

James Ogden
A: 

@James Ogden. This is not true. There is also a Lossless JPEG encoding method.

GateKiller
+11  A: 
var qualityEncoder = Encoder.Quality;
var quality = (long)<desired quality>;
var ratio = new EncoderParameter(qualityEncoder, quality );
var codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">;
bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG
aku
What's with the var abuse?
jestro
He's probably a former user of VB.
Geoff
I don't think there's anything wrong with using `var` in this case. It makes the code easier on the eyes.
Deniz Dogan
A: 

Just want to say that JPEG is by nature a lossy format. So in thoery even at the highest settings you are going to have some information loss, but it depends a lot on the image.But png is lossless.

paan
+3  A: 
public static class BitmapExtensions
{
    public static void SaveJPG100(this Bitmap bmp, string filename)
    {            
        EncoderParameters encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
    }

    public static void SaveJPG100(this Bitmap bmp, Stream stream)
    {
        EncoderParameters encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
    }

    public static ImageCodecInfo GetEncoder(ImageFormat format)
    {

        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

        foreach (ImageCodecInfo codec in codecs)
        {
            if (codec.FormatID == format.Guid)
            {
                return codec;
            }
        }
        return null;
    }
jestro