c# - 如何使用 IntPtr 指针从字节数组中获取新的位图?
问题描述
我的方法有问题Marshal.UnsafeAddrOfPinnedArrayElement()
。
我想做的是Bitmap object
从byte[]
数组返回。但首先,下面的一些代码说明我在做什么。
首先,我加载我从它返回数组的
Bitmap
to 方法:byte[]
//return tuple with pointer to array and byte[]array public static (byte[], IntPtr) GetByteArray(Bitmap bitmap) { //lockbits BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat ); int pixels = bitmapData.Stride * bitmap.Height; byte[] resultArray = new byte[pixels]; //copying bytes to array Marshal.Copy(bitmapData.Scan0, resultArray, 0, pixels); bitmap.UnlockBits(bitmapData); //returns array and pointer to it return (resultArray, bitmapData.Scan0); }
其次,我想编辑那个字节数组:
public static Bitmap Execute(Bitmap bitmap, int[] filter) { //get byte array from method that i mentioned before with pointer to it (byte[] pixelsFromBitmap, IntPtr pointer) = PictureUtilities.GetByteArray(bitmap); byte[] newPixels = pixelsFromBitmap; int stride = bitmap.Width; int height = bitmap.Height; int width = bitmap.Width; Parallel.For(0, height - 1, y => { int offset = y * stride; for(int x = 0; x < width - 1; x++) { //some stuff i doing with array, not neceserry what im doing here int positionOfPixel = x + offset; newPixels[positionOfPixel] = (byte)122; } }); //copying values from newPixels to pixelsFromBitmap that i get from method GetByteArray() that i mentioned it before newPixels.CopyTo(pixelsFromBitmap, 0); //copying bytes again Marshal.Copy(pixelsFromBitmap, 0, pointer, pixelsFromBitmap.Length); //generete new bitmap from byte array Bitmap result = new Bitmap(bitmap.Width, bitmap.Height, stride, bitmap.PixelFormat, pointer); return result; }
在所有这些过程之后,我得到一个 Exception in Execute()
method: System.ArgumentException
in line,当我得到 new 时Bitmap result
。
你能告诉我,我做错了什么吗?我想从方法中的位图中获取一个字节数组(为了便于阅读),编辑它并返回新的位图取决于我的新字节数组。
我敢打赌,我不清楚是如何工作的,而且我从方法返回时Marshall.Copy
出错了。pointer
byte array
GetByteArray()
感谢帮助
解决方案
推荐阅读
- sql - 如何使用 SQL 索引元素?
- postgresql-9.5 - 在 postgreSQL 中创建数据库链接
- flask - 使用 mod_wsgi 在 apache 上提供 Flask 应用程序来考虑文件路径的正确方法是什么
- python - 有没有办法重写函数 data1.groupby(level=0)['total_tax'],apply(lambda x: x.shift()) 以避免设置复制警告
- jquery - jquery没有找到当前li的img src
- design-patterns - 传递部分完整的构建器实例
- react-native - 推送到堆栈只工作一次 - React Native Navigation V2
- python - 如何确保绘图的 x 轴和 y 轴大小相等?
- vba - 在 Access 2016 中计算对数趋势线端点值
- java - 处理迭代多个集合所需的 lambda 集合问题帮助