Nic*_*ick 258
看看这个链接:http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing [<== Link is DEAD]
private static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ant 223
您可以使用Graphics.DrawImage
从位图将裁剪的图像绘制到图形对象上.
Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
using(Graphics g = Graphics.FromImage(target))
{
g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*sJJ 48
比接受的答案更简单的是:
public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
{
Bitmap nb = new Bitmap(r.Width, r.Height);
Graphics g = Graphics.FromImage(nb);
g.DrawImage(b, -r.X, -r.Y);
return nb;
}
Run Code Online (Sandbox Code Playgroud)
并且它避免了最简单答案的" 内存不足 "异常风险.
编辑:我发现这可以保存Bitmap.Save
或由Paint.exe 保存的PNG ,但由于例如Paint Shop Pro 6保存的PNG失败- 内容被取代.添加GraphicsUnit.Pixel
会产生不同的错误结果.也许只是这些失败的PNG是错误的.
小智 7
使用bmp.SetResolution(image.HorizontalResolution,image .VerticalResolution);
这可能是必要的,即使你在这里实现最佳答案,特别是如果你的图像真的很棒,分辨率不是96.0
我的测试示例:
static Bitmap LoadImage()
{
return (Bitmap)Bitmap.FromFile( @"e:\Tests\d_bigImage.bmp" ); // here is large image 9222x9222 pixels and 95.96 dpi resolutions
}
static void TestBigImagePartDrawing()
{
using( var absentRectangleImage = LoadImage() )
{
using( var currentTile = new Bitmap( 256, 256 ) )
{
currentTile.SetResolution(absentRectangleImage.HorizontalResolution, absentRectangleImage.VerticalResolution);
using( var currentTileGraphics = Graphics.FromImage( currentTile ) )
{
currentTileGraphics.Clear( Color.Black );
var absentRectangleArea = new Rectangle( 3, 8963, 256, 256 );
currentTileGraphics.DrawImage( absentRectangleImage, 0, 0, absentRectangleArea, GraphicsUnit.Pixel );
}
currentTile.Save(@"e:\Tests\Tile.bmp");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是裁剪图像的简单示例
public Image Crop(string img, int width, int height, int x, int y)
{
try
{
Image image = Image.FromFile(img);
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
bmp.SetResolution(80, 60);
Graphics gfx = Graphics.FromImage(bmp);
gfx.SmoothingMode = SmoothingMode.AntiAlias;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
// Dispose to free up resources
image.Dispose();
bmp.Dispose();
gfx.Dispose();
return bmp;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
这很容易:
Bitmap
使用裁剪大小创建一个新对象.Graphics.FromImage
创建Graphics
对象的新位图.DrawImage
方法将图像绘制到具有负X和Y坐标的位图上.