我使用以下代码在C#中制作图像蒙版:
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建议的链接删除,危险站点后,我使用以下代码使其工作(对于任何需要它的人):
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表示该像素没有透明度。
我相信您可以很容易地修改绘制矩形的循环:)
发布于 2019-08-28 10:31:09
你仍然可以通过减少写操作来大大加速你的循环。
在缓冲区中创建单行字节,并要求.net运行时将这些字节复制到托管内存。这在我的电脑上大约快了10-15倍。
// 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);
如果你想保持你的“每个像素一个循环迭代”,你至少应该只写每个像素值一次。这会将我计算机上的运行时间减半。
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;
}
}
}
https://stackoverflow.com/questions/7433508
复制相似问题