如何从具有负步幅的位图中复制像素数据?
- 作者: 关婕妍
- 来源: 51数据库
- 2022-10-20
问题描述
我一直在寻找将位图转换为 8bpp 的最快方法.我找到了两种方法:
I was looking for the fastest way to convert a Bitmap to 8bpp. I found 2 ways:
1.
public static System.Drawing.Image ConvertTo8bpp(Bitmap oldbmp)
{
using (var ms = new MemoryStream())
{
oldbmp.Save(ms, ImageFormat.Gif);
ms.Position = 0;
return System.Drawing.Image.FromStream(ms);
}
}
2. http://www.wischik.com/lu/programmer/1bpp.html
但是:1. 结果质量非常低(托盘不良)
But: 1. Results in a very low quality result (bad pallet)
和 2 给了我一个负步幅的位图,当我尝试锁定位并将数据复制到字节数组时,我得到一个异常:尝试读取或写入受保护的内存.这通常表明其他内存已损坏.
and 2 gives me a Bitmap with negative stride, when I try to lockbits and copy the data to a byte array I get an exception: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
this.stride = bmpData.Stride;
this.bytesPerPixel = GetBytesPerPixel(bmp.PixelFormat);
int length = bmpData.Stride * bmp.Height;
if (this.stride < 0)
this.data = new byte[-length];
else
this.data = new byte[length];
Marshal.Copy(bmpData.Scan0, data, 0, length);
//Unlock the bitmap
bmp.UnlockBits(bmpData);
我怎样才能让 2 取得积极的进展?或者如何使用负步幅的锁位复制数据?
How can I make 2 gives a positive stride? Or how can I copy data using lockbits of a negative stride??
推荐答案
一次复制 1 行,计算一行的起始指针为 ((byte*)scan0 + (y * stride))代码>.无论是正步幅还是负步幅,代码都是相同的.
Copy 1 row at a time, calculating the starting pointer for a row as ((byte*)scan0 + (y * stride)). The code will be identical for either positive or negative stride.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
