首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用不安全代码的C#位图图像掩模

使用不安全代码的C#位图图像掩模
EN

Stack Overflow用户
提问于 2011-09-15 23:35:04
回答 1查看 9.3K关注 0票数 22

我使用以下代码在C#中制作图像蒙版:

代码语言:javascript
复制
for(int x = 0; x < width; x++)
{
    for(int y = 0; y < height; y++)
    {
        bmp.SetPixel(x,y,Color.White);
    }
}

for(int x = left; x < width; x++)
{
    for(int y = top; y < height; y++)
    {
        bmp.SetPixel(x,y,Color.Transparent);
    }
}

但是太慢了.与此对应的不安全因素是什么?会不会分配得更快?

最后,我做了一个PNG格式的bmp.Save()。

更新:

在阅读了MusiGenesis建议的链接删除,危险站点后,我使用以下代码使其工作(对于任何需要它的人):

代码语言:javascript
复制
Bitmap     bmp = new Bitmap(1000,1000,PixelFormat.Format32bppArgb);
BitmapData bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width,bmp.Height), 
                                  System.Drawing.Imaging.ImageLockMode.ReadWrite, 
                                  bmp.PixelFormat);

int PixelSize=4;

unsafe 
{
    for(int y=0; y<bmd.Height; y++)
    {
        byte* row=(byte *)bmd.Scan0+(y*bmd.Stride);

        for(int x=0; x<bmd.Width; x++)
        {
            row[x*PixelSize]     = 0;   //Blue  0-255
            row[x*PixelSize + 1] = 255; //Green 0-255
            row[x*PixelSize + 2] = 0;   //Red   0-255
            row[x*PixelSize + 3] = 50;  //Alpha 0-255
        }
    }
}

bmp.UnlockBits(bmd);

bmp.Save("test.png",ImageFormat.Png);

Alpha通道:0表示完全透明,255表示该像素没有透明度。

我相信您可以很容易地修改绘制矩形的循环:)

EN

回答 1

Stack Overflow用户

发布于 2019-08-28 10:31:09

你仍然可以通过减少写操作来大大加速你的循环。

在缓冲区中创建单行字节,并要求.net运行时将这些字节复制到托管内存。这在我的电脑上大约快了10-15倍。

代码语言:javascript
复制
// Build a "row" array and copy once for each row
// You can also build the full byte array and do only one
// call to Marshal.Copy, but that of course takes more memory.

var bytesPerPixel = 4;
byte[] row = new byte[bmp.Width * bytesPerPixel];
for (var i = 0; i < bmp.Width; ++i)
{
    var offset = i * bytesPerPixel;

    row[offset+0] = 0; //Blue  0-255
    row[offset+1] = 255; //Green 0-255
    row[offset+2] = 0;   //Red   0-255
    row[offset+3] = 50;  //Alpha 0-255
}

var bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
for (var i = 0; i < bits.Height; ++i)
{
    Marshal.Copy(row, 0, bits.Scan0 + (i * bits.Stride), row.Length);
}
bmp.UnlockBits(bits);

如果你想保持你的“每个像素一个循环迭代”,你至少应该只写每个像素值一次。这会将我计算机上的运行时间减半。

代码语言:javascript
复制
var pixel = (uint)(a << 24) | (uint)(r << 16) | (uint)(g << 8) | (b);
unsafe
{
    for (int y = 0; y < bmd.Height; y++)
    {
        var row = (uint*) ((byte*)bmd.Scan0 + (y * bmd.Stride));

        for (int x = 0; x < bmd.Width; x++)
        {
            row[x] = pixel;
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7433508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档