I want to crop the image on the fly in c#.
I have referred some links and implement like following.
Reference:
- http://www.c-sharpcorner.com/blogs/resizing-image-in-c-sharp-without-losing-quality1
- http://www.c-sharpcorner.com/blogs/resizing-image-in-c-sharp-without-losing-quality1
But I am getting the low quality image. I have seen website they are uploading the image in their server and scale down the website without losing quality
How have they done? Why can't we do in c#?
CODE
public static Image ScaleImage(Image image, int width, int height)
{
if (image.Height < height && image.Width < width) return image;
using (image)
{
double xRatio = (double)image.Width / width;
double yRatio = (double)image.Height / height;
double ratio = Math.Max(xRatio, yRatio);
int nnx = (int)Math.Floor(image.Width / xRatio);
int nny = (int)Math.Floor(image.Height / yRatio);
Bitmap resizedImage = new Bitmap(nnx, nny, PixelFormat.Format64bppArgb);
using (Graphics graphics = Graphics.FromImage(resizedImage))
{
graphics.Clear(Color.Transparent);
// This is said to give best quality when resizing images
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(image,
new Rectangle(0, 0, nnx, nny),
new Rectangle(0, 0, image.Width, image.Height),
GraphicsUnit.Pixel);
}
return resizedImage;
}
}