user924387
user924387

Reputation: 123

NSData -> UIImage -> NSData

I have an NSData object, which contains RGB values for an image. I want to turn that into a UIImage (given the width and the height). Then I want to convert that UIImage back into an NSData object identical to the one I started with.

Please help me I've been trying for hours now.

Here are some things I've looked at/tried though probably didn't too them right cause it didn't work:

CGImageCreate
CGBitmapContextCreateWithData
CGBitmapContextGetData
CGDataProviderCopyData(CGImageGetDataProvider(imageRef))

Thanks!

Here is my current code:

NSMutableData *rgb; //made earlier
double len = (double)[rgb length];
len /= 3;
len += 0.5;
len = (int)len;
int diff = len*3-[rgb length];
NSString *str = @"a";
NSData *a = [str dataUsingEncoding:NSUTF8StringEncoding];
for(int i =0; i < diff; i++) {
    [toEncode appendData:a]; //so if my data is RGBRGBR it will turn into RGBRGBR(97)(97)
}
size_t width = (size_t)len;
size_t height = 1;
CGContextRef ctx; 
CFDataRef m_DataRef;
m_DataRef = (__bridge CFDataRef)toEncode;
UInt8 * m_PixelBuf = (UInt8 *) CFDataGetBytePtr(m_DataRef); 
vImage_Buffer src;
src.data = m_PixelBuf;
src.width = width;
src.height = height;
src.rowBytes = 3 * width;
vImage_Buffer dst;
dst.width = width;
dst.height = height;
dst.rowBytes = 4 * width;
vImageConvert_RGB888toARGB8888(&src, NULL, 0, &dst, NO, kvImageNoFlags);
//    free(m_PixelBuf);
//    m_PixelBuf = dst.data;
//    NSUInteger lenB = len * (4/3);
/*
 UInt8 * m_Pixel = malloc(sizeof(UInt8) * lenB);
 int z = 0;
 for(int i = 0; i < lenB; i++) {
 if(i % 4==0) {
 m_Pixel[i] = 0;
 } else {
 m_Pixel[i] = m_PixelBuf[z];
 z++;            
 }
 }*/
//    Byte tmpByte; 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
/*
 ctx = CGBitmapContextCreate(m_PixelBuf, 
 width, 
 height, 
 8, 
 4*width, 
 colorSpace, 
 kCGImageAlphaPremultipliedFirst ); 
 */
size_t w = (size_t)len;
ctx = CGBitmapContextCreate(dst.data, 
                            w, 
                            height, 
                            8, 
                            4*width, 
                            colorSpace, 
                            kCGImageAlphaNoneSkipFirst );     
CGImageRef imageRef = CGBitmapContextCreateImage (ctx); 
UIImage* rawImage = [UIImage imageWithCGImage:imageRef]; 

CGContextRelease(ctx); 

I get this error:<Error>: CGBitmapContextCreate: invalid data bytes/row: should be at least 324 for 8 integer bits/component, 3 components, kCGImageAlphaNoneSkipFirst.

Upvotes: 2

Views: 3771

Answers (4)

nessence
nessence

Reputation: 579

The error stating that rowBytes needs to be at least 324; dividing that by 4 is 81 which implies that 'width' is smaller than 'w', and that w=81. The two values should match.

Try replacing width and w with a small number like 5 to validate this. I would also note that you should be allocating dst.data via malloc prior to calling vImageConvert_RGB888toARGB8888.

Consider using CGImageCreate() instead of creating a bitmapcontext:

// this will automatically free() dst.data when destData is dealloc
NSData *destData = [NSData dataWithBytesNoCopy:dst.data length:4*width*height];
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)destData);
CGImageRef imageRef = CGImageCreate(width,
                                    height,
                                    8,                          //bits per component
                                    8*4,                        //bits per pixel
                                    4*width,                    //bytesPerRow
                                    colorSpace,                 //colorspace
                                    kCGImageAlphaNoneSkipFirst,
                                    provider,                   //CGDataProviderRef
                                    NULL,                       //decode
                                    false,                      //should interpolate
                                    kCGRenderingIntentDefault   //intent
                                    );

Upvotes: 0

Jeshua Lacock
Jeshua Lacock

Reputation: 6668

If your data is in RGB format, you will want to create a bitmap using CGBitmapContextCreate with CGColorSpaceCreateDeviceRGB and using kCGImageAlphaNone.

Upvotes: 0

omz
omz

Reputation: 53551

The basic procedure would be to create a bitmap context using CGBitmapContextCreateWithData and then creating a CGImageRef from that with CGBitmapContextCreateImage. The parameters for creating the bitmap context depend on how your raw data is laid out in memory. Not all kinds of raw data are supported by Quartz.

The documentation on CGBitmapContextCreateWithData is quite detailed, and this is the most challenging part, getting the CGImageRef from the context and wrapping that in a UIImage (imageWithCGImage:) is trivial afterwards.

Upvotes: 2

Jeremy
Jeremy

Reputation: 9010

TO UIImage from NSData:

[UIImage imageWithData:]

More on UIImage

TO NSData from UIImage:

UIImage *img = [UIImage imageNamed:@"some.png"];
NSData *dataObj = UIImageJPEGRepresentation(img, 1.0);

More on UIImageJPEGRepresentation()

Upvotes: 5

Related Questions