Creating a UIImage from another UIImage using imageWithData returns nil

I am trying to extract image data from one uiimage, modify it and create a new uiimage from it. To start, I tried just copying the data without any changes to weaken the basics, but it fails ( UIImage +imageWithData:returns zero). Can anyone understand why this will not work?

// 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]; 

Note:

I also tried using:

UInt8 * data = CFDataGetBytePtr (dataRef);

and just lay pipelines directly to NSData.

The same result.

+5
source share
1 answer

, 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;

( : - , - . , .)

+1

All Articles