3
votes

I am having trouble in converting NSData to a UIImage.

I capture an image from the device camera, and convert this image into NSData to store it in SQLite using the BLOB data type.

The image data is successfully stored in the DB, but when I retrieve my image data, the application crashes.

I use this code:

NSData *tempData = [[NSData alloc] init];
tempData = [[arr_img objectAtIndex:indexPath.row] valueForKey:@"Image"];

UIImage *img = [[UIImage alloc] initWithData:tempData];

and get this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString bytes]: unrecognized selector sent to instance 0x5f8c000'

What am I doing wrong?

2
how do you store NSData in sqlite ?Hector
Why do you alloc/init to write over tempData immediately?Sergey Kalinichenko
There must be something wrong in your data!!!Nikhil Bansal
@Hector:i Store my data using this line app.picdata = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];kb920

2 Answers

1
votes

You can do it in this way

NSData *data = yourData;
UIImage *image = [UIImage imageWithData:data];

or

NSData *data = yourData;
UIImage *image = [[UIImage alloc] initWithData:data];
[image release];

if it does work means there may be some prob in the value of ur NSData

1
votes

Insert image into SQLite:

sqlite3_bind_blob(compiledStatement,i, [image_data bytes], [image_data length], SQLITE_TRANSIENT);

and Get image from SQLite:

NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, i) length: sqlite3_column_bytes(compiledStatement, i)];           
UIImage *img = [UIImage imageWithData:dataForCachedImage];

Here 'i' is your database column number