2017-06-20 137 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