如何使用IntPtr指针从字节数组中获取新的位图?

时间:2018-11-13 09:41:21

标签: c# arrays image interop marshalling

我对Marshal.UnsafeAddrOfPinnedArrayElement()方法有疑问。

我想做的是从Bitmap object数组返回byte[]。但是首先,下面一些代码说明了我的工作。

  1. 首先,我将Bitmap加载到从中返回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);
    }
    
  2. 第二,我要编辑该字节数组:

    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;
    
    
    }
    

所有这些过程之后,当我获得新的Execute()时,我在System.ArgumentException方法中得到了一个异常:Bitmap result

你能告诉我,我做错了什么吗?我想从方法的位图中获取字节数组(出于可读性),对其进行编辑,然后根据我的新字节数组返回新的位图。

我敢打赌,我无法清楚地了解Marshall.Copy的工作方式,并且我错误地pointerbyte array方法返回GetByteArray()

感谢帮助

0 个答案:

没有答案
相关问题