High-Quality Image Resizing in C#
Resizing images in C# often involves using the System.Drawing.Image
class's Size
, Width
, and Height
properties. However, a simple resizing approach can compromise image quality. For optimal results, employ a more sophisticated method like the one below:
public static Bitmap ResizeImage(Image image, int width, int height) { var destRect = new Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } return destImage; }
This method leverages several key features to ensure high-quality resizing:
wrapMode.SetWrapMode(WrapMode.TileFlipXY)
: Eliminates artifacts (ghosting) at image edges by mirroring the image during the scaling process.destImage.SetResolution(...)
: Preserves the image's DPI (dots per inch), crucial for maintaining quality when reducing size or preparing for print.CompositingQuality
, InterpolationMode
, SmoothingMode
, and PixelOffsetMode
are all set to HighQuality
or HighQualityBicubic
for superior rendering.Important Considerations:
This function doesn't inherently manage aspect ratio; you'll need to handle that aspect yourself to prevent distortion. Furthermore, remember that saving the resized image (e.g., using destImage.Save(...)
) can also impact quality. Consult external resources for best practices in image saving formats and compression levels.
The above is the detailed content of How to Resize Images in C# While Maintaining Optimal Quality?. For more information, please follow other related articles on the PHP Chinese website!