简体   繁体   English

从NSData创建UiImage

[英]Create UiImage from NSData

Below is code I copied (from this site) and modified only slightly since the original code would not compile. 下面是我复制的代码(来自这个网站)并且只是稍微修改,因为原始代码无法编译。 I want to manipulate the byte array for edge detection and eventually simple changes to colors, but first I wanted to get the basic code working. 我想操纵字节数组进行边缘检测并最终简单地改变颜色,但首先我想让基本代码工作。 Currently, the system compiles and runs. 目前,系统编译并运行。 It displays a badly drawn elephant on screen. 它在屏幕上显示一幅画得很厉害的大象。 When I touch the image, it disappears. 当我触摸图像时,它会消失。 Stepping through shows the result of imageWithData as 0x0. 单步执行将imageWithData的结果显示为0x0。 I have tried this with both a png and a bmp and same result 我用png和bmp尝试了同样的结果

Any clues to what I am doing wrong ?! 我做错了什么线索?!

ImageViewDrawable is defined as: 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: doesn't take some arbitrary data and interpret it as an RGBA uncompressed texture. imageWithData:不接受任意数据并将其解释为RGBA未压缩纹理。 It takes a data that contains bytes of a recognized image format (like JPG, PNG, or TIFF), parses thoses and decompresses the images appropriately. 它需要包含已识别图像格式(如JPG,PNG或TIFF)的字节的数据,解析thoses并适当地解压缩图像。

In order to do what you want you need to create a CGContext which is appropriately configured (row bytes, pixel format, etc), either using the memory you already have allocated as its backing storage, or by asking it for its storage and then copying your bytes into it. 为了做你想做的事,你需要创建一个适当配置的CGContext(行字节,像素格式等),或者使用你已经分配作为其后备存储的内存,或者通过询问它的存储然后复制你的字节进入它。 Once you do that you can use all of the CGContext related functionality, including the ability to create a UIImage from that context. 完成后,您可以使用所有与CGContext相关的功能,包括从该上下文创建UIImage的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM