1

I tried this:

string str = System.IO.Path.GetFileName(txtImage.Text);
string pth = System.IO.Directory.GetCurrentDirectory() + "\\Subject";
string fullpath = pth + "\\" + str;

Image NewImage = clsImage.ResizeImage(fullpath, 130, 140, true);
NewImage.Save(fullpath, ImageFormat.Jpeg); 

public static Image ResizeImage(string file, int width, int height, bool onlyResizeIfWider)
{
    if (File.Exists(file) == false)
        return null;
    try
    {
        using (Image image = Image.FromFile(file))
        {
            // Prevent using images internal thumbnail
            image.RotateFlip(RotateFlipType.Rotate180FlipNone);
            image.RotateFlip(RotateFlipType.Rotate180FlipNone);
            if (onlyResizeIfWider == true)
            {
                if (image.Width <= width)
                {
                    width = image.Width;
                }
            }
            int newHeight = image.Height * width / image.Width;
            if (newHeight > height)
            {
                // Resize with height instead
                width = image.Width * height / image.Height;
                newHeight = height;
            }
            Image NewImage = image.GetThumbnailImage(width, newHeight, null, IntPtr.Zero);
            return NewImage;
        }
    }
    catch (Exception )
    {
        return null;
    }
}

Running the above code, I get an image 4-5 KB in size with very poor image quality. The original image file is no more than 1.5 MB large. How can I improve the image quality of the results?

Adam
  • 15,537
  • 2
  • 42
  • 63
Krunal Mevada
  • 1,637
  • 1
  • 17
  • 28
  • 1
    Your use of `RotateFlip` is strange. I see the comment, but this just looks like cargo cult programming to me. – Oded Jul 07 '12 at 12:59
  • 1
    Which `Image` class are you using? In what namespace? When saving, use an overload that takes `EncoderParameters` with a quality setting of `High`. – Oded Jul 07 '12 at 13:01
  • can you give me the link for that @Oded – Krunal Mevada Jul 07 '12 at 13:53
  • The RotateFlip actually prevents GetThumbnailImage from using the embedded thumbnail, but it still produces horrible quality results. – Lilith River Jul 07 '12 at 14:18

1 Answers1

4

I think you should use Image Resizer, its free and resizing an image is very easy using it.

var settings = new ResizeSettings {
MaxWidth = thumbnailSize,
MaxHeight = thumbnailSize,
Format = "jpg"
};
settings.Add("quality", quality.ToString());
ImageBuilder.Current.Build(inStream, outStream, settings);
resized = outStream.ToArray(); 

You can also install it using Nuget package manager.

PM> Install-Package ImageResizer
Lilith River
  • 16,204
  • 2
  • 44
  • 76
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42