【问题标题】:Cast Graphics to Image in C#在 C# 中将图形转换为图像
【发布时间】:2011-02-07 01:39:18
【问题描述】:

我在 Windows 窗体上有一个图片框。

我执行以下操作以将 PNG 文件加载到其中。

Bitmap bm = (Bitmap)Image.FromFile("Image.PNG", true);
Bitmap tmp;

public Form1() {
    InitializeComponent();
    this.tmp = new Bitmap(bm.Width, bm.Height);
}

private void pictureBox1_Paint(object sender, PaintEventArgs e) {
    e.Graphics.DrawImage(this.bm, new Rectangle(0, 0, tmp.Width, tmp.Height), 0, 0, tmp.Width, tmp.Height, GraphicsUnit.Pixel);
}

但是,我需要在图像上绘制东西,然后再次显示结果。绘制矩形只能通过 Graphics 类来完成。

我需要在图像上绘制所需的矩形,再次使其成为 Image 类的实例并将其保存到 this.bm

我可以添加一个执行this.pictureBox1.Refresh(); 的按钮,强制重新绘制pictureBox,但我不能将Graphics 转换为Image。因此,我无法将编辑保存到this.bm 位图。

这是我的问题,我看不到出路。

【问题讨论】:

    标签: c# image graphics


    【解决方案1】:

    您需要做的是使用Graphics.FromImage 方法,这将允许您直接在图像上绘制,而不是从Paint 方法中创建的临时Graphics 对象:

    using (Graphics g = Graphics.FromImage(this.bm))
    {
        g.DrawRectangle(...);
    }
    

    这样做而不是(或附加于)挂钩PictureBoxPaint 方法。这样,您根本不需要使用临时图像或Graphics 对象,并且当您完成修改原始位图(this.bm)后,您可以调用pictureBox1.Refresh 来强制图像重新-显示。

    【讨论】:

    • 我一直想知道为什么当我在我的 Paint(object sender, PaintEventArgs e) 方法中使用 e.Graphics 进行绘制时,图形不是图像的一部分。感谢您提供有关如何直接在图像上绘图的提示!
    猜你喜欢
    • 2017-10-08
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多