[英]Crop Image C# Distorsion
I am trying to crop an image with C# but i have some problem. 我正在尝试使用C#裁剪图像,但是我遇到了一些问题。
I need to crop this image and remove 15 pixels from top: 我需要裁剪此图像并从顶部删除15个像素:
I have used this code: 我使用了以下代码:
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);
This is the first image quality with a zoom: 这是具有变焦的第一个图像质量:
and this the second: 这是第二个:
How can i have the same image quality? 如何获得相同的图像质量?
The problem is that you are grabbing a rectangle higher than what fits in the bitmap (the second Size
parameter is the size, not the bottom-right coordinates), so it's scaling it: 问题在于,您正在抓取一个比位图合适的矩形(第二个
Size
参数是大小,而不是右下角的坐标),因此它正在缩放它:
Rectangle destRectangle = new Rectangle(
new Point(0, 15), new Size(myBitmap.Width, myBitmap.Height-15));
This should work... since it's not actually the dest
rectangle, but the source
rectangle on the DrawImage
call 这应该起作用...因为它实际上不是
dest
矩形,而是DrawImage
调用上的source
矩形
Other way to crop, which doesn't even need a Graphics
object might be: 甚至不需要
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);
If you use this method, make 100% sure that the crop rectangle doesn't cross the bounds of the original image, since Clone
will throw an exception if it does. 如果您使用此方法,请确保100%确保裁剪矩形没有越过原始图像的边界,因为
Clone
会抛出异常。
Try to paste 尝试粘贴
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
before calling DrawImage 在调用DrawImage之前
or use 或使用
g.DrawImageUnscaled(myBitmap, new Point(0, -15));
Try to use ImageProcessor framework. 尝试使用ImageProcessor框架。 It can handle this easily using .Quality() method.
它可以使用.Quality()方法轻松处理此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.