To optimize image handling in ASP.NET for performance improvement, you can follow several best practices. Here's a sample code that demonstrates some of these optimizations:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
public class ImageHelper
{
public static void ResizeImage(string sourcePath, string outputPath, int maxWidth, int maxHeight)
{
using (var sourceImage = Image.FromFile(sourcePath))
{
int newWidth, newHeight;
CalculateDimensions(sourceImage.Width, sourceImage.Height, maxWidth, maxHeight, out newWidth, out newHeight);
using (var thumbnail = new Bitmap(newWidth, newHeight))
{
using (var graphic = Graphics.FromImage(thumbnail))
{
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(sourceImage, 0, 0, newWidth, newHeight);
}
// Save the resized image to the output path
thumbnail.Save(outputPath, ImageFormat.Jpeg);
}
}
}
private static void CalculateDimensions(int originalWidth, int originalHeight, int maxWidth, int maxHeight, out int newWidth, out int newHeight)
{
double widthRatio = (double)maxWidth / originalWidth;
double heightRatio = (double)maxHeight / originalHeight;
double ratio = Math.Min(widthRatio, heightRatio);
newWidth = (int)(originalWidth * ratio);
newHeight = (int)(originalHeight * ratio);
}
}
In this code, we have a ResizeImage
method that takes the source image path, output path, maximum width, and maximum height as parameters. It resizes the image while maintaining its aspect ratio.
Here are the optimizations included in this sample code:
Dispose of resources: The
using
statement ensures thatImage
,Bitmap
, andGraphics
objects are disposed of properly after use, preventing resource leaks.Interpolation mode: The
InterpolationMode.HighQualityBicubic
setting improves the image resizing quality.Smoothing mode: The
SmoothingMode.HighQuality
setting improves the quality of anti-aliasing.Pixel offset mode: The
PixelOffsetMode.HighQuality
setting ensures high-quality pixel rendering.Compositing quality: The
CompositingQuality.HighQuality
setting improves the quality of image composition.JPEG output format: In this example, the resized image is saved in the JPEG format, but you can change it to the desired format.
To use this code, you can call the ResizeImage
method and provide the appropriate parameters:
string sourcePath = Server.MapPath("~/Images/source.jpg");
string outputPath = Server.MapPath("~/Images/resized.jpg");
int maxWidth = 800;
int maxHeight = 600;
ImageHelper.ResizeImage(sourcePath, outputPath, maxWidth, maxHeight);
Make sure to adjust the source and output paths and define appropriate maximum width and height values for your specific use case.
Comments
Post a Comment