2014-01-06 43 views
0

算術此代碼應該讓我的每一個像素的值從CGImageRef開始:閱讀像素字節:一個指向不完全類型

UIImage* image = [UIImage imageNamed:@"mask.bmp"]; 
CGImageRef aCGImageRef = image.CGImage; 

CFDataRef rawData = CGDataProviderCopyData(CGImageGetDataProvider(aCGImageRef)); 
UInt8 * buf = (UInt8 *) CFDataGetBytePtr(rawData); 
int length = CFDataGetLength(rawData); 

CFRelease(rawData); 

int no_of_channels = 3; 
int image_width = SCREEN_WIDTH(); 

unsigned long row_stride = image_width * no_of_channels; // 960 bytes in this case 
unsigned long x_offset = x * no_of_channels; 

/* assuming RGB byte order (as opposed to BGR) */ 
UInt8 r = *(rawData + row_stride * y + x_offset); 
UInt8 g = *(rawData + row_stride * y + x_offset + 1); 
UInt8 b = *(rawData + row_stride * y + x_offset + 2); 

這最後三個行會做的伎倆,但編譯器說,將不會這樣做xy作爲float s。所以我鑄造他們int,但現在它說

算術上的指針不完整的類型爲const結構__CFData

我該如何解決呢?

回答

3

您希望對字節指針本身執行算術操作,而不是對CFData結構(將字節作爲成員)進行計算。這意味着使用buf變量上面:

UInt8 r = *(buf + row_stride * y + x_offset); 
UInt8 g = *(buf + row_stride * y + x_offset + 1); 
UInt8 b = *(buf + row_stride * y + x_offset + 2); 
+3

+1,但我還會注意到:OP不應該'CFRelease(RAWDATA)'之前訪問的字節數。不能保證'buf'在這之後仍然是一個有效的指針。 –

+0

好注意,@KenThomases,謝謝。我錯過了。 –

+1

換句話說:@RickON,請記住,代碼中的rawData指的是CFData對象,而不是該對象中的原始數據*。 'buf'(數據對象的字節指針)是指向實際原始數據的指針。 –