简体   繁体   中英

resize image in asp.net

I have this code to resize an image but the image doesn't look so good:

public Bitmap ProportionallyResizeBitmap(Bitmap src, int maxWidth, int maxHeight)
{

    // original dimensions
    int w = src.Width;
    int h = src.Height;
    // Longest and shortest dimension
    int longestDimension = (w > h) ? w : h;
    int shortestDimension = (w < h) ? w : h;
    // propotionality
    float factor = ((float)longestDimension) / shortestDimension;
    // default width is greater than height
    double newWidth = maxWidth;
    double newHeight = maxWidth / factor;
    // if height greater than width recalculate
    if (w < h)
    {
        newWidth = maxHeight / factor;
        newHeight = maxHeight;
    }
    // Create new Bitmap at new dimensions
    Bitmap result = new Bitmap((int)newWidth, (int)newHeight);
    using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
        g.DrawImage(src, 0, 0, (int)newWidth, (int)newHeight);
    return result;
}

Try setting the InterpolationMode of the graphics object to some value such as HighQualityBicubic . This should ensure that resize/scaled image looks much better than the "default".

So, in the code you have posted, instead of doing:

// Create new Bitmap at new dimensions
Bitmap result = new Bitmap((int)newWidth, (int)newHeight);
using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
   g.DrawImage(src, 0, 0, (int)newWidth, (int)newHeight);
return result;

Try doing this instead:

// Create new Bitmap at new dimensions
Bitmap result = new Bitmap((int)newWidth, (int)newHeight);
using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
{
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(src, 0, 0, (int)newWidth, (int)newHeight);
}
return result;

(Note the line setting the InterpolationMode property to one of the InterpolationMode enumeration's values).

Please see this link:
How to: Use Interpolation Mode to Control Image Quality During Scaling
For further information on controlling the quality of an image when resizing/scaling.

Also see this CodeProject article:
Resizing a Photographic image with GDI+ for .NET
For information of the different visual effects the various InterpolationMode enumeration settings will have on an image. (About two-thirds of the way down the article, under the section entitled, "One last thing...").

If you need an on-the-fly resize I suggest you to try an HttpHandler I write recently, I've posted the code on my blog (sorry, but is in italian).

With some modifies you can use the code also for save the transformed image on the disk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM