从NSData创建UiImage

6 iphone byte uiimageview uiimage 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 ]; 
}
Run Code Online (Sandbox Code Playgroud)

Lou*_*arg 4

imageWithData:不接受一些任意数据并将其解释为 RGBA 未压缩纹理。它获取包含可识别图像格式(如 JPG、PNG 或 TIFF)字节的数据,解析这些数据并适当解压缩图像。

为了执行您想要的操作,您需要创建一个适当配置的 CGContext(行字节、像素格式等),或者使用您已经分配的内存作为其后备存储,或者通过询问其存储然后复制你的字节到它里面。一旦你这样做了,你就可以使用所有 CGContext 相关的功能,包括从该上下文创建 UIImage 的能力。