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

标签 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* 数据 = CFDataGetBytePtr(dataRef);

然后直接将其传输到 NSData 中。

相同的结果。

最佳答案

我相信 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 的示例。聪明的部分是她的;错误都是我的。但这是总体思路,应该可行。)

关于iphone - 使用 imageWithData 从另一个 UIImage 创建 UIImage 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3367628/

相关文章:

ios - 如何获取 UIImage 中形状的 UIBezierPath 或以特定形状裁剪 UIImage

ios - 在另一个 View Controller 中传递 ImagePickerView 的图像

ios - 在 ios 中首次启动时, View 会全黑几秒钟, swift

iphone - 使用 CALayer 绘制虚线

iphone - 为什么 CSS 不启动 max-device-width : 480px?

iphone - 无法禁用 CALayer>>removeFromSuperlayer 的动画

ios - 在 Swift 中合并两个不同的图像

iphone - 用大写字母对 NSArray 进行排序

iphone - 如何以编程方式在 iOS/iPad 上启动隐藏的应用程序?

objective-c - 使用 UIImage 黑白 iOS 屏蔽 UIView