【发布时间】:2017-02-22 13:22:16
【问题描述】:
我想在 c# 中即时裁剪图像。
我已经参考了一些链接并实现如下。
参考:
- 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
但我得到的是低质量的图像。我见过他们在他们的服务器上上传图片并在不损失质量的情况下缩小网站的网站
他们做得怎么样?为什么我们不能在 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;
}
}
【问题讨论】:
-
我过去遇到过这个问题并解决了,但我不记得我和 ATM 是如何工作的。我不知何故想说你可以将它转换为 JPEG,缩小它,然后再回到位图,因为我认为位图的缩放不是那么好......我什至不确定我是如何做到的,但感觉就像是我做到了。已经好几年了...除非您测试并看到它,否则我会调查它,这会有所帮助。
-
Resize an Image C#的可能重复
-
裁剪不应损失质量。如果你缩小它,你总是会丢失信息。确保两张图片的相同的dpi设置!! - 见here for a similar problem。注意第二部分! - 还有see here about your pixelformat
-
你试过了吗?使用 DrawImage 获得正确的结果需要这点:
Bitmap resizedImage = new Bitmap(nnx, nny, PixelFormat.???); resizedImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);