上下文:我有一个获取任何图像的ArGB的程序。把它扔进Color ARGBFormat = Color.FromArgb(alpha, red, green, blue);
现在我想把它放到PictureBox中。我没有完整的像素阵列(它或多或少分散)。
代码:
Bitmap bmp = new Bitmap(ImagePath);
Rectangle bmpRec = new Rectangle(0, 0, bmp.Width, bmp.Height); //Creates Rectangle for holding picture
BitmapData bmpData = bmp.LockBits(bmpRec, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); //Gets the Bitmap data
IntPtr Pointer = bmpData.Scan0;
int DataBytes = Math.Abs(bmpData.Stride) * bmp.Height; //Gets array size
byte[] rgbValues = new byte[DataBytes]; //Creates array
Marshal.Copy(Pointer, rgbValues, 0, DataBytes); //Copies of out memory
StringBuilder EveryPixel = new StringBuilder(" ");
int PixelSize = 4;
Color ARGBFormat;
Bitmap ImageOut = new Bitmap(bmp.Width, bmp.Height);
unsafe
{
for (int y = 0; y < bmpData.Height; y++)
{
byte* row = (byte*)bmpData.Scan0 + (y * bmpData.Stride);
for (int x = 0; x < bmpData.Width; x++)
{
int offSet = x * PixelSize;
// read pixels
byte blue = row[offSet];
byte green = row[offSet + 1];
byte red = row[offSet + 2];
byte alpha = row[offSet + 3];
ARGBFormat = Color.FromArgb(alpha, red, green, blue);
ImageOut.SetPixel(x, y, ARGBFormat); //Slow
EveryPixel.Append(ARGBFormat);
}
}
}
我想使用我一直在使用的代码^在不使用SetPixels的情况下显示到PictureBox中。我想使用LockBits,因为它是最优化的方法。
答案 0 :(得分:0)
你去吧
循环前的初始化代码
BitmapData bitmapData = ImageOut.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
byte[] pixels = new byte[bmp.Width * bmp.Height * 4]; //4 means 1 byte for each a r g b
IntPtr ptr = bitmapData.Scan0;
Marshal.Copy(ptr , pixels, 0, pixels.Length);
更新循环中的像素
pixels[offSet] = blue;
pixels[offSet + 1] = green;
pixels[offSet + 2] = red;
pixels[offSet + 3] = alpha;
最后清理代码
bitmapData.UnlockBits();
所以对我来说代码看起来像
unsafe
{
BitmapData bitmapData = ImageOut.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
byte[] pixels = new byte[bmp.Width * bmp.Height * 4]; //4 means 1 byte for each a r g b
IntPtr ptr = bitmapData.Scan0;
Marshal.Copy(ptr , pixels, 0, pixels.Length);
for (int y = 0; y < bmpData.Height; y++)
{
byte* row = (byte*)bmpData.Scan0 + (y * bmpData.Stride);
for (int x = 0; x < bmpData.Width; x++)
{
int offSet = x * PixelSize;
// read pixels
byte blue = row[offSet];
byte green = row[offSet + 1];
byte red = row[offSet + 2];
byte alpha = row[offSet + 3];
//copy to target
pixels[offSet] = blue;
pixels[offSet + 1] = green;
pixels[offSet + 2] = red;
pixels[offSet + 3] = alpha;
}
}
bitmapData.UnlockBits();
}
//set to picturebox
pictureBox.Image = ImageOut;
我希望这对你有用。