2016-04-21 114 views
1

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

我需要裁剪这张图片并从顶部15个像素:enter image description here

我已经使用这个代码:

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); 
Graphics g = Graphics.FromImage(bmp); 
g.DrawImage(myBitmap, 0, 0, destRectangle, GraphicsUnit.Pixel); 
bmp.Save(outputFileNameCut, ImageFormat.Jpeg); 

outputFileName是第一个图像的路径和outputFileNameCut路径为新图片。它工作正常,但是当我保存图像,保存的图像是这样:

enter image description here

似乎也是质量比较少。无论是图像的.jpg

谢谢

+0

不要对这样的图像使用JPG。对于像条形码这样的东西,PNG是无损和完美的。也就是说,你不是裁剪 - 你正在重新调整。您还需要使用源矩形来裁剪图像。 – Luaan

+0

当你说'庄稼'时,你的意思是'删除左侧和右侧的空白'?此外,它看起来像你没有解决你的合成矩形高度的变化。不应该是myBitmap.Height - 15? – ManoDestra

+0

我用过png,但是我总是有一个无损的质量 – Ale

回答

2

使用此代码来代替:

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.Jpeg); 

在一个侧面说明,这可能使条形码无效使用。因为您正在修改和调整图像大小,可能会在某种程度上干扰某些扫描仪。