开发者

iPhone - UIImage imageWithData returning nil

开发者 https://www.devze.com 2023-02-14 05:58 出处:网络
I need to create an UIImage from a byte array. Here is now I create the byte array: image = CGImageCreateWithImageInRect(aux.CGImage, imageRect);

I need to create an UIImage from a byte array. Here is now I create the byte array:

image = CGImageCreateWithImageInRect(aux.CGImage, imageRect);
context = CGBitmapContextCreate (data[i][j], TILE_WIDTH, TILE_HEIGHT, 
                                 bitsPerComponent, bitmapBytesPerRow, colorSpace,
                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);//kCGImageAlphaNoneSkipFirst);//kCGImageAlphaNone);//

CGContextDrawImage(context, CGRectMake(0, 0, TILE_WIDTH, TILE_HEIGHT), image);

data[i][j] = CGBitmapContextGetData (context);

The data variable is an unsigned char.

And this is how I try to get the UIImage:

NSData *imgD开发者_开发问答ata = [NSData dataWithBytes:data[i][j] length:TILE_WIDTH*TILE_HEIGHT*numberOfCompponents];
        UIImage *img = [UIImage imageWithData: imgData];

The img (UIImage) is remaining nil.

OK, not this is the background: I am trying to create a pixelate application :). The images from the iPhone 4 camera are too big in size, so I split the image in smaller images. Doing so, when the area pixelated (touched) needs to be updated in order for the pixelate effect to be displayed, I am updating a smaller UIImage. I needed to do it like this because in previous tests it seamed like the update of an UIImage is killing the CPU. Still, the smaller images are now around 80x100 pxl, and the update is not working as smooth as possible. Sometimes, if you move the finger to fast it misses some spots :D. I think that using this method to create an UIImage from the byte array is faster than this one:

CGImageRef cgImage = CGImageCreate(TILE_WIDTH, TILE_HEIGHT, bitsPerComponent,
                                   bitsPerPixel, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big, 
                                   dataProvider, NULL, false, kCGRenderingIntentDefault);
UIImage *imageToBeUpdated = [UIImage imageWithCGImage:cgImage];

Am I correct?


[UIImage imageWithData:data] parses data that is in a known image file format (e.g. jpeg, png, or gif; full list in the documentation. You're passing it raw pixel data, which is not supported.

Try this instead of CGBitmapContextGetData to get the image out of the context:

CGImageRef imgRef = CGBitmapContextCreateImage(context);
UIImage *img = [UIImage imageWithCGImage:imgRef];
0

精彩评论

暂无评论...
验证码 换一张
取 消