如何在 Xamarin iOS 中获取 CGBitmap 的像素数据作为 byte[]

How to get pixel data of CGBitmap as byte[] in Xamarin iOS

我有 CGBitmap 个实例(每像素 32 位),我想在 byte[].

中获取图像数据

字节数组应获得 ARGB 格式的值,因此前 4 个字节对应于每个 alpha 图像字节中的第一个像素,红色、绿色和蓝色 值。

这是一个想法。图片是 UIImage

        CGImage imageRef = image.CGImage;
        int width = (int)image.Size.Width;
        int height = (int)image.Size.Height;
        CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();
        byte[] rawData = new byte[height * width * 4];
        int bytesPerPixel = 4;
        int bytesPerRow = bytesPerPixel * width;
        int bitsPerComponent = 8;
        CGContext context = new CGBitmapContext(rawData, width, height,
                        bitsPerComponent, bytesPerRow, colorSpace,
                        CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big);

        context.DrawImage((CGRect)new CGRect(0, 0, width, height), (CGImage)imageRef);     

        // Now your rawData contains the image data in the RGBA8888 pixel format.
        int pixelInfo = (width * y + x) * 4; // The image is png
        //red,green, blue,alpha
        byte red = rawData[pixelInfo];
        byte green = rawData[pixelInfo+1];
        byte blue = rawData[pixelInfo+2];
        byte alpha = rawData[pixelInfo + 3];