簡體   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