我需要使用带有 LockBits 的图像处理而不是 GetPixel/SetPixel 来减少处理时间。但最终它不会保存所有更改。
重现问题的步骤:
- 从初始 bmp 文件中读取所有字节;
- 更改所有这些字节并将其保存到新文件中;
- 读取保存的文件并将其数据与您尝试保存的数据进行比较。
预期:它们是相等的,但实际上它们不是。
我注意到(见输出):
- 所有错误的值都等于 0,
- 错误值的索引如下:x1, x1+1, x2, x2+1, ...,
- 对于某些文件,它可以按预期工作。
更令人困惑的事情是:我的初始测试文件是灰色的,但在 HexEditor 中,在预期的有效负载值中,我们可以看到值“00 00”。见这里。 这意味着什么?
我在 Stack Overflow、MSDN、CodeProject 和其他网站上阅读并尝试了很多 LockBits 教程,但最终它的工作方式相同。
所以,这里是代码示例。的代码MyGetByteArrayByImageFile
和UpdateAllBytes
直接来自 msdn 文章“如何:使用 LockBits”(方法MakeMoreBlue
),有一些小的改动:硬编码的像素格式被替换,每个字节都在变化(而不是每 6 个)。
内容Program.cs
:
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace Test
{
class Program
{
const int MagicNumber = 43;
static void Main(string[] args)
{
//Arrange
string containerFilePath = "d:/test-images/initial-5.bmp";
Bitmap containerImage = new Bitmap(containerFilePath);
//Act
Bitmap resultImage = UpdateAllBytes(containerImage);
string resultFilePath = "d:/test-result-images/result-5.bmp";
resultImage.Save(resultFilePath, ImageFormat.Bmp);
//Assert
var savedImage = new Bitmap(resultFilePath);
byte[] actualBytes = savedImage.MyGetByteArrayByImageFile(ImageLockMode.ReadOnly).Item1;
int count = 0;
for (int i = 0; i < actualBytes.Length; i++)
{
if (actualBytes[i] != MagicNumber)
{
count++;
Debug.WriteLine($"Index: {i}. Expected value: {MagicNumber}, but was: {actualBytes[i]};");
}
}
Debug.WriteLine($"Amount of different bytes: {count}");
}
private static Bitmap UpdateAllBytes(Bitmap bitmap)
{
Tuple<byte[], BitmapData> containerTuple = bitmap.MyGetByteArrayByImageFile(ImageLockMode.ReadWrite);
byte[] bytes = containerTuple.Item1;
BitmapData bitmapData = containerTuple.Item2;
// Manipulate the bitmap, such as changing all the values of every pixel in the bitmap
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = MagicNumber;
}
// Copy the RGB values back to the bitmap
Marshal.Copy(bytes, 0, bitmapData.Scan0, bytes.Length);
// Unlock the bits.
bitmap.UnlockBits(bitmapData);
return bitmap;
}
}
}
内容ImageExtensions.cs
:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace Test
{
public static class ImageExtensions
{
public static Tuple<byte[], BitmapData> MyGetByteArrayByImageFile(this Bitmap bmp, ImageLockMode imageLockMode = ImageLockMode.ReadWrite)
{
// Specify a pixel format.
PixelFormat pxf = bmp.PixelFormat;//PixelFormat.Format24bppRgb;
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, imageLockMode, pxf);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
// int numBytes = bmp.Width * bmp.Height * 3;
int numBytes = bmpData.Stride * bmp.Height;
byte[] rgbValues = new byte[numBytes];
// Copy the RGB values into the array.
Marshal.Copy(ptr, rgbValues, 0, numBytes);
return new Tuple<byte[], BitmapData>(rgbValues, bmpData);
}
}
}
输出示例:
Index: 162. Expected value: 43, but was: 0;
Index: 163. Expected value: 43, but was: 0;
Index: 326. Expected value: 43, but was: 0;
Index: 327. Expected value: 43, but was: 0;
Index: 490. Expected value: 43, but was: 0;
Index: 491. Expected value: 43, but was: 0;
Index: 654. Expected value: 43, but was: 0;
...
Index: 3606. Expected value: 43, but was: 0;
Index: 3607. Expected value: 43, but was: 0;
Index: 3770. Expected value: 43, but was: 0;
Index: 3771. Expected value: 43, but was: 0;
Amount of different bytes: 46
如果有人能解释为什么会发生这种情况以及如何解决这个问题,我将不胜感激。非常感谢。
解决方案
根据Joshua Webb 的回答,我更改了代码:
在文件Program.cs
中,我只更改UpdateAllBytes
了使用新扩展方法的方法UpdateBitmapPayloadBytes
:
private static Bitmap UpdateAllBytes(Bitmap bitmap)
{
Tuple<byte[], BitmapData> containerTuple = bitmap.MyGetByteArrayByImageFile(ImageLockMode.ReadWrite);
byte[] bytes = containerTuple.Item1;
BitmapData bitmapData = containerTuple.Item2;
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = MagicNumber;
}
bitmap.UpdateBitmapPayloadBytes(bytes, bitmapData);
return bitmap;
}
ImageExtensions.cs:
public static class ImageExtensions
{
public static Tuple<byte[], BitmapData> MyGetByteArrayByImageFile(this Bitmap bmp, ImageLockMode imageLockMode = ImageLockMode.ReadWrite)
{
PixelFormat pxf = bmp.PixelFormat;
int depth = Image.GetPixelFormatSize(pxf);
CheckImageDepth(depth);
int bytesPerPixel = depth / 8;
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bitmapData = bmp.LockBits(rect, imageLockMode, pxf);
// Get the address of the first line.
IntPtr ptr = bitmapData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int rowPayloadLength = bitmapData.Width * bytesPerPixel;
int payloadLength = rowPayloadLength * bmp.Height;
byte[] payloadValues = new byte[payloadLength];
// Copy the values into the array.
for (var r = 0; r < bmp.Height; r++)
{
Marshal.Copy(ptr, payloadValues, r * rowPayloadLength, rowPayloadLength);
ptr += bitmapData.Stride;
}
return new Tuple<byte[], BitmapData>(payloadValues, bitmapData);
}
public static void UpdateBitmapPayloadBytes(this Bitmap bmp, byte[] bytes, BitmapData bitmapData)
{
PixelFormat pxf = bmp.PixelFormat;
int depth = Image.GetPixelFormatSize(pxf);
CheckImageDepth(depth);
int bytesPerPixel = depth / 8;
IntPtr ptr = bitmapData.Scan0;
int rowPayloadLength = bitmapData.Width * bytesPerPixel;
if(bytes.Length != bmp.Height * rowPayloadLength)
{
//to prevent ArgumentOutOfRangeException in Marshal.Copy
throw new ArgumentException("Wrong bytes length.", nameof(bytes));
}
for (var r = 0; r < bmp.Height; r++)
{
Marshal.Copy(bytes, r * rowPayloadLength, ptr, rowPayloadLength);
ptr += bitmapData.Stride;
}
// Unlock the bits.
bmp.UnlockBits(bitmapData);
}
private static void CheckImageDepth(int depth)
{
//Because my task requires such restrictions
if (depth != 8 && depth != 24 && depth != 32)
{
throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");
}
}
}
此代码通过了图像测试:
- 8、24、32 bpp;
- 当需要而不是填充字节时(例如,width = 63, bpp = 24 and width = 64, bpp = 24, ...)。
在我的任务中,我不必关心我正在更改哪些值,但是如果您需要计算红色、绿色、蓝色值的确切位置,请记住字节按 BGR 顺序排列,如答案中所述。