我想用c#裁剪图像

本文关键字:裁剪 图像 | 更新日期: 2023-09-27 18:07:08

我是c#新手。我不知道怎么了…请修复错误,使此代码将工作。我想用c#裁剪图像。当这段代码工作时,我将研究它。

https://ideone.com/ljkaWZ

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
    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;
}

ideone.com说:

prog.cs(13,10): error CS1514: Unexpected symbol `public', expecting `.' or `{'
prog.cs(13,18): error CS1525: Unexpected symbol `Bitmap', expecting `class', `delegate', `enum', `interface',      
`partial', or `struct'
Compilation failed: 2 error(s), 0 warnings

我想用c#裁剪图像

如果你想裁剪图像,你可以指定一个source矩形和一个destination矩形。在您的示例中,r将是源,在下面给定的示例中,destRect将是创建新位图的目标。

public static Bitmap cropAtRect(Bitmap b, Rectangle r)
{
    Bitmap nb = new Bitmap(r.Width, r.Height);
    Graphics g = Graphics.FromImage(nb);
    Rectangle destRect = new Rectangle(0, 0, r.Width, r.Height); //Set destination rect
    g.DrawImage(b, destRect, r, GraphicsUnit.Pixel);
    return nb;
}

当然,你应该验证给定的r(源矩形)是否在b(源位图)的范围内。

我也不确定你是否正在学习通过this创建extension方法。但是现在上面的示例应该可以用于裁剪图像。一定要学会正确的语法