2

i save an image in Database. i am trying to get the image and export it into a CSV file. I use following code to convert into string but it returns null.

   int length = sqlite3_column_bytes(compiledStatement, i); 
   NSData *img =[NSData dataWithBytes:sqlite3_column_blob(compiledStatement, i) length:length];
   text = [[NSString alloc] initWithData:img encoding:NSUTF8StringEncoding];

   NSLog(@"ColName : %@, TEXT : %@",colName, text); //Text displayed is (NULL)

when i am saving the image, i convert the image to NSData and then insert it in database column. The datatype of column, in which image is saved, is "blob".

Thanks in advance.

2 Answers2

2

The encoding argument to initWithData:encoding: specifies what the encoding of the data is, not what the String will be. If the data is not actually UTF-8 then the conversion will fail and the string returned will be null.

Seeing as your data is binary it is almost a 100% guarantee that the conversion is encountering invalid UTF-8 byte sequences and aborting.

Though I do not recommend serializing image data to Strings, if you absolutely must do it then you should Base-64 encode the data first, as described in this SO post.

Community
  • 1
  • 1
Perception
  • 79,279
  • 19
  • 185
  • 195
1

Maybe try to use for take image from data

[NSKeyedUnarchiver unarchiveObjectWithData:yourData]

And to save to your data

 NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:yourObject];

I use it for saving images and other contents to my Core Data.

Neznajka
  • 305
  • 5
  • 19