0

Possible Duplicate:
Resizing an Image without losing any quality

The code I always use on my applications, after user uploads image from FileUpload and save on the server reducing the size, is good. But when I do the same thing on photoshop(manually) and uploading a file on facebook the quality is whey better and the reduced size is very fair.

I just can't figure how can I improve the quality of my uploaded images on the server, does anybody use a different approach?

see code below:

        private static byte[] ReturnReducedImage(byte[] original, int width, int height)
    {
        Image img = RezizeImage(Image.FromStream(BytearrayToStream(original)), width, height);
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }


    private static Image RezizeImage(Image img, int maxWidth, int maxHeight)
    {
        if (img.Height < maxHeight && img.Width < maxWidth) return img;
        Bitmap cpy = null;
        using (img)
        {
            Double xRatio = (double)img.Width / maxWidth;
            Double yRatio = (double)img.Height / maxHeight;
            Double ratio = Math.Max(xRatio, yRatio);
            int nnx = (int)Math.Floor(img.Width / ratio);
            int nny = (int)Math.Floor(img.Height / ratio);
            cpy = new Bitmap(nnx, nny);
            using (Graphics gr = Graphics.FromImage(cpy))
            {
                gr.Clear(Color.Transparent);
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                gr.DrawImage(img, new Rectangle(0, 0, nnx, nny), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
            }
        }
        return cpy;
    }
Community
  • 1
  • 1
RollRoll
  • 8,133
  • 20
  • 76
  • 135

1 Answers1

2

I believe this answers the question: https://stackoverflow.com/a/87786/910348.

You'll want to replace this:

using (Graphics gr = Graphics.FromImage(cpy))
{
    gr.Clear(Color.Transparent);
    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
    gr.DrawImage(img, new Rectangle(0, 0, nnx, nny), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
}

with something like this:

using (Graphics gr = Graphics.FromImage(cpy))
{
    gr.Clear(Color.Transparent);
    gr.SmoothingMode = SmoothingMode.AntiAlias;
    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
    gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
    gr.DrawImage(img, new Rectangle(0, 0, nnx, nny));
}

Cheers.

Community
  • 1
  • 1
ThisGuy
  • 2,335
  • 1
  • 28
  • 34