繁体   English   中英

裁剪图像C#失真

[英]Crop Image C# Distorsion

我正在尝试使用C#裁剪图像,但是我遇到了一些问题。

我需要裁剪此图像并从顶部删除15个像素:

我使用了以下代码:

Bitmap myBitmap = new Bitmap(outputFileName);
Rectangle destRectangle = new Rectangle(new Point(0, 15),
new Size(myBitmap.Width, myBitmap.Height));
Bitmap bmp = new Bitmap(myBitmap.Width, myBitmap.Height - 15);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(myBitmap, 0, 0, destRectangle, GraphicsUnit.Pixel);
bmp.Save(outputFileNameCut, ImageFormat.Png);

这是具有变焦的第一个图像质量:

在此处输入图片说明

这是第二个:

在此处输入图片说明

如何获得相同的图像质量?

问题在于,您正在抓取一个比位图合适的矩形(第二个Size参数是大小,而不是右下角的坐标),因此它正在缩放它:

Rectangle destRectangle = new Rectangle(
       new Point(0, 15), new Size(myBitmap.Width, myBitmap.Height-15));

这应该起作用...因为它实际上不是dest矩形,而是DrawImage调用上的source矩形

甚至不需要Graphics对象的另一种裁剪方法可能是:

Bitmap myBitmap = new Bitmap(outputFileName);
Rectangle srcRectangle = new Rectangle(
       new Point(0, 15), new Size(myBitmap.Width, myBitmap.Height-15));
Bitmap croppedBitmap = myBitmap.Clone(srcRectangle, myBitmap.PixelFormat);
croppedBitmap.Save(outputFileNameCut, ImageFormat.Png);

如果您使用此方法,请确保100%确保裁剪矩形没有越过原始图像的边界,因为Clone会抛出异常。

尝试粘贴

g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

在调用DrawImage之前

或使用

g.DrawImageUnscaled(myBitmap, new Point(0, -15));

尝试使用ImageProcessor框架。 它可以使用.Quality()方法轻松处理此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM