0

I am converting NSData of Image from database to NSString in iPhone

Here is my code

imageData1 = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 2) length: sqlite3_column_bytes(compiledStatement, 2)];           
NSLog(@"the data length %d",[imageData1 length]);
NSString* newStr1 = [[NSString alloc] initWithData:imageData1 encoding:NSUTF8StringEncoding];

The length of data is 6511 , but the newstr1 is nil

With reference to this stack overflow question. I can't create a UTF-8 encoded string out of just any arbitrary binary data from the database - the data needs to actually be UTF-8 encoded. I need it in the format of NSString only, to give it as input to a CSV file.

EDIT:

imageData1 = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 3) length: sqlite3_column_bytes(compiledStatement, 3)];           
NSString * Str1 = [NSString base64StringFromData: imageData1 length: [imageData1 length]];
NSData *data1=[NSData base64DataFromString:Str1];
NSString* newStr1 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];

After base 64 encoding and decoding also my string is nil.

halfer
  • 19,824
  • 17
  • 99
  • 186
Warrior
  • 39,156
  • 44
  • 139
  • 214

1 Answers1

3

Chances are very good that you don't actually want to dump raw binary data into a CSV file. You probably want to look into base64-encoding the data instead. This previous answer should be able to help you with that.

Community
  • 1
  • 1
Anomie
  • 92,546
  • 13
  • 126
  • 145
  • 1
    NSString is intended to contain text, not arbitrary binary data. A CSV file is also more suited to text than arbitrary binary data, and throwing arbitrary binary data in there might confuse various other programs that try to read your file. The "base64" encoding transforms binary data to a text string using only letters, numbers, and a limited set of punctuation that is safe for storing in things that expect plain text. – Anomie Mar 03 '11 at 16:23
  • I send the base64 encoded string in the csv file, it is opened as text only and not as image? – Warrior Mar 04 '11 at 07:34
  • Most tools reading a CSV file would read the binary data as garbled text rather than as an image too. – Anomie Mar 04 '11 at 12:06