使用imageWithData从另一个UIImage创建UIImage将返回nil

时间:2010-07-29 22:59:18

标签: iphone uiimage

我正在尝试从一个uiimage中检索图像数据,修改它,并从中创建一个新的uiimage。首先,我尝试复制数据而不进行任何修改以使基础知识失效 - 但失败(UIImage +imageWithData:返回nil)。任何人都可以看到为什么这不起作用?

// I've confirmed that the follow line works

UIImage *image = [UIImage imageNamed:@"image_foo.png"];

// Get a reference to the data, appears to work

CFDataRef dataRef = CGDataProviderCopyData(CGImageGetDataProvider([image CGImage]));

// Get the length of memory to allocate, seems to work (e.g. 190000)

int length = CFDataGetLength(dataRef) * sizeof(UInt8);

UInt8 * buff = malloc(length);

// Again, appears to work 

CFDataGetBytes(dataRef, CFRangeMake(0,length),buff);

// Again, appears to work

NSData * newData = [NSData dataWithBytesNoCopy:buff length:length];

// This fails by returning nil

UIImage *image2 = [UIImage imageWithData:newData]; 

注意:

我也尝试过使用:

UInt8 * data = CFDataGetBytePtr(dataRef);

直接将其直接导入NSData。

结果相同。

1 个答案:

答案 0 :(得分:1)

我相信imageWithData需要图像文件数据,而不是图像显示数据,这就是你传递的内容。尝试这样的事情:

NSData * newData = UIImageJPEGRepresentation(image, 1.0);
UIImage *image2 = [UIImage imageWithData:newData]; 

UIImageJPegRepresentation()返回您要写入文件的数据,以便在磁盘上创建.jpg文件。那,我99.44%肯定是imageWithData:想要的。

注意:如果你想在创建image2之前操纵数据,那么你想要显示数据,在这种情况下你从中获取图像的方式有点复杂,但看起来像这样:

    // Create a color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color space\n");
        return nil;
    }

    CGContextRef context = CGBitmapContextCreate (bits, size.width, size.height,
            8, size.width * 4, colorSpace,
            kCGImageAlphaPremultipliedLast | IMAGE_BYTE_ORDER
            );
    CGColorSpaceRelease(colorSpace );

    if (context == NULL)
    {
        fprintf (stderr, "Error: Context not created!");
        return nil;
    }

    CGImageRef ref = CGBitmapContextCreateImage(context);
    //free(CGBitmapContextGetData(context));                                      //* this appears to free bits -- probably not mine to free!
    CGContextRelease(context);

    UIImage *img = [UIImage imageWithCGImage:ref];
    CFRelease(ref);                                                             //* ?!?! Bug in 3.0 simulator.  Run in 3.1 or higher.

    return img;

(上面的代码来自Erica Sadun的例子。聪明的部分是她的;错误都是我的。但这是一般的想法,它应该有效。)

相关问题