也许这样的事情会更快。推理,Getbits 和Setbits 非常慢,每个都在内部调用锁定位来锁定内部存储器。最好一次性全部完成
使用LockBits、unsafe、fixed 和Dictionary
为了测试结果,我使用了这张图片
来自
我根据您的原始版本测试结果,它们是相同的
基准测试
----------------------------------------------------------------------------
Mode : Release (64Bit)
Test Framework : .NET Framework 4.7.1 (CLR 4.0.30319.42000)
----------------------------------------------------------------------------
Operating System : Microsoft Windows 10 Pro
Version : 10.0.17134
----------------------------------------------------------------------------
CPU Name : Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz
Description : Intel64 Family 6 Model 42 Stepping 7
Cores (Threads) : 4 (8) : Architecture : x64
Clock Speed : 3401 MHz : Bus Speed : 100 MHz
L2Cache : 1 MB : L3Cache : 8 MB
----------------------------------------------------------------------------
测试 1
--- Random Set ------------------------------------------------------------
| Value | Average | Fastest | Cycles | Garbage | Test | Gain |
--- Scale 1 ------------------------------------------------ Time 8.894 ---
| Mine1 | 5.211 ms | 4.913 ms | 17.713 M | 0.000 B | Pass | 93.50 % |
| Original | 80.107 ms | 75.131 ms | 272.423 M | 0.000 B | Base | 0.00 % |
---------------------------------------------------------------------------
完整代码
public unsafe byte[] Convert(string input)
{
using (var bmp = new Bitmap(input))
{
var pixels = bmp.Palette.Entries.Select((color, i) => new {x = color,i})
.ToDictionary(arg => arg.x.ToArgb(), x => x.i);
// lock the image data for direct access
var bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
// create array as we know the size
var data = new byte[bmp.Height * bmp.Width];
// pin the data array
fixed (byte* pData = data)
{
// just getting a pointer we can increment
var d = pData;
// store the max length so we don't have to recalculate it
var length = (int*)bits.Scan0 + bmp.Height * bmp.Width;
// Iterate through the scanlines of the image as contiguous memory by pointer
for (var p = (int*)bits.Scan0; p < length; p++, d++)
//the magic, get the pixel, lookup the Dict, assign the values
*d = (byte)pixels[*p];
}
// unlock the bitmap
bmp.UnlockBits(bits);
return data;
}
}
总结
无论如何,我都不是图像专家,如果这不起作用,那么您的索引图像可能会有所不同,我不明白
更新
要检查像素格式,如果它有调色板,您可以使用以下方法
bmp.PixelFormat
bmp.Palette.Entries.Any()
更新2
Vlad i Slav 的工作解决方案如下
我需要将 PixelFormat.Format32bppPArgb 替换为 Format32bppArgb 和
添加此检查
if (pixels.ContainsKey(*p))
*d = (byte)pixels[*p];
else
*d = 0;.
还需要从调色板中获取不同的值,因为我一直
在那里给出一些错误。