[英]Create UiImage from NSData
下面是我復制的代碼(來自這個網站)並且只是稍微修改,因為原始代碼無法編譯。 我想操縱字節數組進行邊緣檢測並最終簡單地改變顏色,但首先我想讓基本代碼工作。 目前,系統編譯並運行。 它在屏幕上顯示一幅畫得很厲害的大象。 當我觸摸圖像時,它會消失。 單步執行將imageWithData的結果顯示為0x0。 我用png和bmp嘗試了同樣的結果
我做錯了什么線索?!
ImageViewDrawable定義為:
@interface ImageViewDrawable : UIImageView
// I am using the following code to initialize this ImageView
ImageViewDrawable * uiv = [[ImageViewDrawable alloc] initWithImage:[UIImage imageNamed:@"ele.png"] ];
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// get and work on pixel data
NSData* pixelData = (NSData*) CGDataProviderCopyData(CGImageGetDataProvider(self.image.CGImage));
char* bytes =[pixelData bytes];
// Take away the red pixel, assuming 32-bit RGBA
for(int i = 0; i < [pixelData length]; i += 4) {
bytes[i] = bytes[i]; // red
bytes[i+1] = bytes[i+1]; // green
bytes[i+2] = bytes[i+2]; // blue
bytes[i+3] = bytes[i+3]; // alpha
}
// convert pixel back to uiiimage
NSData* newPixelData = [NSData dataWithBytes:bytes length:[pixelData length]];
char * bytes2 =[pixelData bytes];
UIImage * newImage = [UIImage imageWithData:newPixelData] ;
[self setImage: newImage ];
}
imageWithData:不接受任意數據並將其解釋為RGBA未壓縮紋理。 它需要包含已識別圖像格式(如JPG,PNG或TIFF)的字節的數據,解析thoses並適當地解壓縮圖像。
為了做你想做的事,你需要創建一個適當配置的CGContext(行字節,像素格式等),或者使用你已經分配作為其后備存儲的內存,或者通過詢問它的存儲然后復制你的字節進入它。 完成后,您可以使用所有與CGContext相關的功能,包括從該上下文創建UIImage的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.