Is this possible? UIImage > NSData > NSString > .txt file

Discussion in 'iOS Programming' started by AndyCodez, Apr 21, 2010.

  1. AndyCodez macrumors regular

    Aug 6, 2009
    I'm Exporting data to a text file and I'm wondering if anyone has done this.

    Convert UIImage to NSData, represent the NSdata as nsstring, and then write the the string to the textfile. Then when reading the file back in its able to reverse that back into an image.

    I could be misinterpreting how nsdata works but has anyone ever done this?
  2. jnic macrumors 6502a

    Oct 24, 2008
    It's certainly possible, but seems like overkill depending on what you're trying to achieve.

    If you just want to cache images then why not just convert the UIImage to NSData and write it to NSUserDefaults?

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *data = UIImagePNGRepresentation(image);
    [defaults setObject:data forKey:@"key"];
    NSData *data = [defaults dataForKey:@"key"];
    UIImage *image = [UIImage imageWithData:data];
    For export, you could use a JSON library for iPhone like SBJSON, or Base64-encode your images.

    For converting NSString and NSData back and forth, you can use:

    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  3. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
  4. AndyCodez thread starter macrumors regular

    Aug 6, 2009
    Thanks for confirming it :)

    Well in my application I'm enabling the user to export their decks of cards to google docs which is stored as Google Doc. Each card consists of question, answer, image, audio. so I'm building the file that would be able to be imported from Google docs. So I think i would need to make it a string to be able to add it to the file properly, (well the current way I am doing it.).

    I'm not actually storing anything in the text file for the app storage this is all done in a sqlite database, this is just for exporting to Google Docs.

    thanks for the responses!
  5. xStep macrumors 68000

    Jan 28, 2003
    Less lost in L.A.
    From your NSData, I'd look at converting it using uuencode and decoding with uudecode. The other option is Base 64. This is common with e-mail applications.
  6. franium macrumors member

    Nov 18, 2010
    Hi, do you succeed in exporting image and text to google docs? I'm trying to use base64 encoding without success.
    Thanks in advance,

Share This Page