首页 > 解决方案 > 如何使用 IntPtr 指针从字节数组中获取新的位图?

问题描述

我的方法有问题Marshal.UnsafeAddrOfPinnedArrayElement()

我想做的是Bitmap objectbyte[]数组返回。但首先,下面的一些代码说明我在做什么。

  1. 首先,我加载我从它返回数组的Bitmapto 方法: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;
    
    
    }
    

在所有这些过程之后,我得到一个 Exception in Execute()method: System.ArgumentExceptionin line,当我得到 new 时Bitmap result

你能告诉我,我做错了什么吗?我想从方法中的位图中获取一个字节数组(为了便于阅读),编辑它并返回新的位图取决于我的新字节数组。

我敢打赌,我不清楚是如何工作的,而且我从方法返回时Marshall.Copy出错了。pointerbyte arrayGetByteArray()

感谢帮助

标签: c#arraysimageinteropmarshalling

解决方案


推荐阅读