Reputation: 3251
I want to crop the image on the fly in c#.
I have referred some links and implement like following.
Reference:
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#?
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;
}
}
Upvotes: 0
Views: 1137
Reputation: 1277
ImageMagick is a viable solution definitely and so is GraphicsMagick or libvips (Though I am not sure if libvips has C# specific bindings but it is a lot faster than IM or GM ).
You may also want to try ImageKit or other similar fully featured third-party image optimisation and delivery solutions to do all this resizing for you.
Upvotes: 0
Reputation: 555
You could try net-vips, the C# binding for libvips. It's a lazy, streaming, demand-driven image processing library, so it can do operations like this without needing to load the whole image.
For example, it comes with a handy image thumbnailer:
Image image = Image.Thumbnail("image.jpg", 300, 300);
image.WriteToFile("my-thumbnail.jpg");
Upvotes: 1
Reputation:
You could use imagemagic for that. It has its own dll to work with VS. It olso have great forum where you can find all kinds of examples. I made a program with it that does that. it took me about half an hour ( not really a big application, it is only used for a commercial company to make a lot of cropped resized pictues (about 4 terrabyte of pictures lol)). here you can find some examples.
https://www.imagemagick.org/script/index.php
Upvotes: 0