2016-04-21 92 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會引發異常。