如何从整数数组创建16位位图?
我有一个整数数组,它将仅包含可以用16位表示的值(值在0-65535范围内)。整数数组是添加了几个8位图像,以使每个图像的所有左上像素的总和是整数数组的第一个元素。我需要在pixelformat.format16bppgrayscale
格式中创建bitmap
对象,但是我不确定该怎么做。我当前的代码在尝试将整数复制到intptr
中时产生system.accessviolationException
。
/// <summary>
/// Converts image int data to bitmap image by creating a compatible bitmap and copying
/// the data. This assumes the int array is a 16 bit image.
/// </summary>
/// <param name="image">Image int data.</param>
/// <param name="width">Width of the image.</param>
/// <param name="height">Height of the image.</param>
/// <param name="pixelFormat">Pixel format of the image.</param>
/// <returns></returns>
public static Bitmap ToBitmap(this int[] image, int width, int height, PixelFormat pixelFormat)
{
// Create a compatible bitmap
var bitmap = new Bitmap(width, height, PixelFormat.Format16bppGrayScale);
// Copy the bits
BitmapData bmData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
IntPtr pNative = bmData.Scan0;
Marshal.Copy(image, 0, pNative, width * height);
bitmap.UnlockBits(bmData);
// Clone into desired format
Bitmap clone = bitmap.Clone(new Rectangle(0, 0, width, height), pixelFormat);
bitmap.Dispose();
return clone;
}
I've got an integer array which will only contain values that can be represented by 16 bits (values will range from 0-65535). The integer array is several 8-bit images added together such that the sum of all of the top left pixels of each image is the first element of the integer array. I need to create a Bitmap
object in the PixelFormat.Format16bppGrayScale
format, but I'm not sure how to do that. My current code yields a System.AccessViolationException
when trying to copy the integers into an IntPtr
.
/// <summary>
/// Converts image int data to bitmap image by creating a compatible bitmap and copying
/// the data. This assumes the int array is a 16 bit image.
/// </summary>
/// <param name="image">Image int data.</param>
/// <param name="width">Width of the image.</param>
/// <param name="height">Height of the image.</param>
/// <param name="pixelFormat">Pixel format of the image.</param>
/// <returns></returns>
public static Bitmap ToBitmap(this int[] image, int width, int height, PixelFormat pixelFormat)
{
// Create a compatible bitmap
var bitmap = new Bitmap(width, height, PixelFormat.Format16bppGrayScale);
// Copy the bits
BitmapData bmData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
IntPtr pNative = bmData.Scan0;
Marshal.Copy(image, 0, pNative, width * height);
bitmap.UnlockBits(bmData);
// Clone into desired format
Bitmap clone = bitmap.Clone(new Rectangle(0, 0, width, height), pixelFormat);
bitmap.Dispose();
return clone;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论