9

I am attempting to support rotating JPEG images from ASP.NET MVC (in 90 degree increments). I am attempting to use System.Drawing (GDI+), however I am running into issues.

I tried using Image.RotateFlip which is able to rotate the image but causes a loss of quality. Even with an encoder quality of 100, there are still visible artifacts on the rotated image that weren't on the original image nor do they show up when I rotate it using other programs (Gimp, etc.).

using (Image image = Image.FromFile("C:\\source.jpg")) {
    ImageFormat sourceFormat = image.RawFormat;
    image.RotateFlip(RotateFlipType.Rotate90FlipNone);
    EncoderParameters encoderParams = null;
    try {
        if (sourceFormat == ImageFormat.Jpeg) {
            encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
        }
        image.Save("C:\\target.jpg", GetEncoder(sourceFormat), encoderParams);
    } finally {
        if (encoderParams != null)
            encoderParams.Dispose();
    }
}

I found an article on transforming a JPEG without loss of information. Using Encoder.Transformation appears to be an option from .NET - however I cannot get it to cause any of my JPEG test images to rotate at all, whether or not the dimensions are a multiple of 16.

using (Image image = Image.FromFile("C:\\source.jpg")) {
    ImageFormat sourceFormat = image.RawFormat;
    EncoderParameters encoderParams = null;
    try {
        if (sourceFormat == ImageFormat.Jpeg) {
            encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(Encoder.Transformation, 
                (long)EncoderValue.TransformRotate90);
        }
        image.Save("C:\\target.jpg", GetEncoder(sourceFormat), encoderParams);
    } finally {
        if (encoderParams != null)
            encoderParams.Dispose();
    }
}

Does anyone know how to successfully rotate a JPEG in .NET in 90 degree increments with minimal or no loss of quality using either of the above methods or another method? Thanks.

Also, here's my implementation of GetEncoder:

private ImageCodecInfo GetEncoder(ImageFormat format) {
    foreach (var info in ImageCodecInfo.GetImageEncoders())
        if (info.FormatID == format.Guid)
            return info;
    return null;
}

Edit:

I updated the above code to better match my actual code. The bug was in the following line:

if (sourceFormat == ImageFormat.Jpeg) {

It should have been:

if (sourceFormat.Guid == ImageFormat.Jpeg.Guid) {
2
  • 2
    Your code works for me.. are you sure an ImageCodecInfo is returned for your data? Jul 27, 2009 at 6:49
  • Thanks @pb, I was getting an ImageCodecInfo but not an encoderParams because my actual code had an additional check before setting it that had a bug.
    – Mike Henry
    Jul 27, 2009 at 7:40

3 Answers 3

4

Thanks for confirming that my posted code worked. This helped me isolate my problem. I feel stupid now. My actual code had a check for image format before setting encoderParams - but it had a bug:

if (sourceFormat == ImageFormat.Jpeg) {
    // set encoderParams here

I discovered the above conditional was always false so encoderParams wasn't being set. The fix was simple:

if (sourceFormat.Guid == ImageFormat.Jpeg.Guid) {
2

With any method that decompresses a lossy compressed image, rotates it and lossy compresses it again (even with same parameter), you will get a loss of quality. During the lossy decompression, you only get an approximation of the lossy compressed image (remember compression is defined in term of PSNR, so another implementation may decompress the same image slightly differently). Same goes for the re-compression, unless you take exactly the same lossy compressor and the same parameters, it is impossible to recompress the image leading to the same quantized DCT values.

The JPEG format compresses color information in squares of 2x2 pixels by getting an average color to represent all four pixels, so if your image width and height are divisible by two you will lose less quality as most of the information removed in the compression is information that was interpolated in the decompression.

Likewise the brightness information is compressed in squares of 8x8 pixels, so if your width and hight are divisable by eight, the grid will align after rotating the image and you will lose less actual information.

To make a lossless rotation you have to use a completely different method, reading the JPEG file and rearranging and rotating each square of information (quantized DCT values) so that it forms the rotated image without decompressing and recompressing it (Entropy Encoding is a lossless mechanism which can safely be round-tripped).

3
  • OP specifically ask for lossless transform and 90° increments with application to JPEG. So it is pretty clear what to do to preserve input quality exactly.
    – malat
    Jun 15, 2021 at 13:45
  • @malat: Yes, I agree that it is pretty clear. That is what I have written in this answer. Is there anything that you disagree with?
    – Guffa
    Jul 5, 2021 at 10:06
  • here is how I would have written it, I believe this is still unclear when rotation can be achieved when using 4:2:0 chroma subsampling, a user may be confused by your reference to 8x8 block reference.
    – malat
    Jul 5, 2021 at 10:38
1

Here's my adaptation of Mike Henry's answer modified to my needs for whoever may find it useful.

public MemoryStream RotateImage(Stream stream, RotateFlipType rotationFlipType)
{
    try
    {
        if (stream != null)
        {
            using (Image image = Image.FromStream(stream))
            {
                ImageFormat sourceFormat = image.RawFormat;
                image.RotateFlip(rotationFlipType);
                EncoderParameters encoderParams = null;
                try
                {
                    if (sourceFormat.Guid == ImageFormat.Jpeg.Guid)
                    {
                        encoderParams = new EncoderParameters(1);
                        encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                    }
                    var ms = new MemoryStream();
                    image.Save(ms,
                        ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatID == sourceFormat.Guid),
                        encoderParams);
                    ms.Position = 0;
                    return ms;
                }
                finally
                {
                    if (encoderParams != null)
                        encoderParams.Dispose();
                }
            }

        }
    }
    finally
    {
        if (stream != null)
        {
            stream.Dispose();
        }
    }
    return null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.