Search code examples
xcodeuiimagepngsparrow-framework

Load .png into xcode and convert to UIImage


I'm completely new to Xcode, obj-c etc, but I want to use Parse.com to save an image to their server, they say you have to use this line, to convert a UIImage to NSData

NSData *imageData = UIImagePNGRepresentation(image);

How would I load one of the .png's that is in my resource folder and then convert it to a UIImage? I'm also using the Sparrow Framework if that helps any.

EDIT

I've tried this code as suggested below.

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"[email protected]" ofType:@"png"];
UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];
NSData *imageData = UIImagePNGRepresentation(myImage);

PFFile *imageFile = [PFFile fileWithName:@"[email protected]" data:imageData];
    [imageFile save];

But nothing seems to be happening. I tried a breakpoint at the last line and the vars imagePath, myImage, imageData are all 00000000 which I don't get.


Solution

  • you should follow code:

    //png
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image" ofType:@"png"];
    UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];
    NSData *pngImageData = UIImagePNGRepresentation(myImage);
    
    //jpeg
    NSString *imagePath2 = [[NSBundle mainBundle] pathForResource:@"your_image" ofType:@"jpg"];
    UIImage *myImage2 = [UIImage imageWithContentsOfFile:imagePath2];
    NSData *jpegImageData = [UIImageJPEGRepresentation(myImage2, 1.0f)];
    

    Do not contain an extension in pathForResource. check following mistake case.

    // not contain an extension

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image.png" ofType:nil];
    

    // contain an extension

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image" ofType:@"png"];
    

    // some people mistake case. wrong code. that return nil

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image.png" ofType:@"png"];