2017-06-20 32 views
0

我有CGBitmap实例(每像素32位),我想要获取图像数据在byte[]如何获取CGBitmap的像素数据为Xamarin iOS中的byte []

的字节数组应该得到的值ARGB格式,以便前4个字节对应于所述第一像素中的每个alpha,红色,绿色和蓝色值的图像字节。

非常感谢!

+0

检查:https://stackoverflow.com/questions/448125/how-to-get-pixel-data-from-a-uiimage-cocoa-touch-or-cgimage-core- 1262893#1262893如果不够清楚,让我知道我会为你提供一个示例代码 –

回答

1

这是一个想法。图像的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]; 
+0

它的工作就像一个魅力!我不明白的是它的工作原理,因为我使用的是ARGB8888,而不是RGBA8888。你确定字节按照你在答案中说的方式排序吗? – SuperJMN

+0

更新了我的答案。这在我的项目中工作 –

+0

好了,现在看起来你的代码中有一部分(最后一部分)在你重新排序字节。但是,它只对一个像素完成(对每个像素应该应用相同的东西)。没有更好的方法来做到这一点吗? – SuperJMN

相关问题