【问题标题】:Create UiImage from NSData从 NSData 创建 UiImage
【发布时间】:2009-09-13 00:22:19
【问题描述】:

下面是我复制的代码(从这个站点),由于原始代码无法编译,因此只做了少许修改。我想操纵字节数组进行边缘检测并最终对颜色进行简单的更改,但首先我想让基本代码正常工作。目前,系统编译运行。它在屏幕上显示一头画得很糟糕的大象。当我触摸图像时,它会消失。单步执行显示 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 ]; 
}

【问题讨论】:

    标签: iphone uiimageview uiimage byte nsdata


    【解决方案1】:

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

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

    【讨论】:

    • 所以我输入的数据基本上来自现有的 UIImage 并不重要?
    • 我看到了我的问题。这组嵌套调用——CGDataProviderCopyData(CGImageGetDataProvider())——获取数据提供者,然后只复制数据。这意味着我只是从原始图像中获取像素而不是其余配置。所以我必须使用这些像素和您提到的 CG 信息重新创建图像。再次感谢您的帮助
    猜你喜欢
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2014-09-13
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    相关资源
    最近更新 更多