简体   繁体   English

如何将 Graphics 对象转换为 Bitmap(或将其作为 Bitmap 访问)

[英]How can I get a convert a Graphics object to a Bitmap (or access it as a Bitmap)

I know the whole我知道整个

Bitmap bmp = new Bitmap(100,100) ;
Graphics graphics = Graphics.FromImage(bmp) ;

But that is not what I need to do.但这不是我需要做的。 Essentially what I am trying to do is slightly modify how something is draw on the screen (it is a rectangle with a line in the middle).基本上我想做的是稍微修改一些东西在屏幕上的绘制方式(它是一个中间有一条线的矩形)。 I need to change the background of the rectangle (which I could do with a pixel comparison or other similar method).我需要改变矩形的背景(我可以用像素比较或其他类似的方法来做)。

If I could somehow turn it into a bitmap.如果我能以某种方式将它变成位图。 There is no way (that I can tell to get/set/modify) the graphics object on the pixel level.没有办法(我可以告诉获取/设置/修改)像素级别的图形对象。

Bob Powell has written an excellent article about accessing image bits directly. Bob Powell 写了一篇关于直接访问图像位的优秀文章。

https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx

You could do this using a for loop like so:您可以使用 for 循环来执行此操作,如下所示:

for(int i = 0; i < bmp.Width; i++)
{
    for(int j = 0; j < bmp.Height; j++)
    {
        var pixel = bmp.GetPixel(i, j);
        //do stuff with pixel here :)
    }
}

EDIT: After seeing Tilak's comment, if performance is an issue for you then he is right!编辑:在看到 Tilak 的评论后,如果性能对你来说是个问题,那么他是对的! (Thanks, I did not know about LockBits! +1) Some examples can be found on the MS BitmapData Class page . (谢谢,我不知道 LockBits!+1)可以在MS BitmapData Class 页面上找到一些示例。 However, if this seems complicated the above method should do the trick :)但是,如果这看起来很复杂,上面的方法应该可以解决问题:)

使用图形后,只需保存位图 - 对图形所做的更改都会对位图进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM