2016-04-21 98 views
0

我想用C#裁剪图像,但我有一些问题。裁剪图像C#Distorion

我需要裁剪这张图片并从顶部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); 

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

enter image description here

and this the second:

enter image description here

我怎样才能获得相同的图像质量?

回答

1

尝试调用的DrawImage

或使用

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

这很完美。非常非常感谢你! – Ale

+0

鉴于两种方法都有效,我想说第二种方法更有意义。改变插值模式和平滑将避免混叠,但问题是首先绘制它的缩放比例,这是不必要的 – Jcl

2

的问题是,你抓比位图(第二Size什么适合高的矩形前粘贴

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

参数是大小,而不是右下角的坐标),所以它的比例是:

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

这应该工作...因为它不是真正的dest矩形,但source矩形的DrawImage呼叫

裁剪的其他方式,这甚至不需要一个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); 

如果使用此方法,请确保裁切矩形不会跨越原始图像的边界,因为Clone会引发异常。