Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone, how does one read an image from the photo library as NSData?

On the iPhone I saved an image to the photo library with modifications (appending data after the image code) using the assest library to save the NSData directly to the photo library. Now I want to read the image back from the photo library as an NSData to read it. If I read it as a UIImage, it changes the data inside the image.

How can I read the photo from the photo library as NSData? I tried looking into the reference URL in 4.1 but no luck.

Edit: I edited to explain why I'm saving it as an NSData. The URL method in the answers works if you just want pure NSData, but does not help in the context that I am asking.

Edit 2: The answer with the getBytes was the answer that did it for me. The code I used was:

int8_t *bytes = malloc([representation size]);
NSUInteger length = [representation getBytes:bytes fromOffset:0 length:[representation size] error:&error];

This was able to get me everything inside the file which gave me the image code PLUS what I added in NSData form.

Edit 3:

Is there a way to do this now in iOS 10 with the PHPhotoLibrary which replaces AssetLibrary? I need the image in NSData being the original RAW image with no modifications.

like image 278
SolidSnake4444 Avatar asked Jul 13 '11 23:07

SolidSnake4444


People also ask

How do you copy the subject of a picture on iPhone?

Open a photo in the Photos app or in apps like Messages or Safari. Touch and hold the subject of the photo. A shiny white outline might appear. Let go to reveal options like Copy and Share in the Photos app or Copy Subject in Safari.


2 Answers

You should look into the getBytes method of ALAssetRepresentation. This gives you the original RAW image data of your image and also makes it possible to use a buffer to process the image instead of reading the image into memory all at once. And of course you can always generate NSData from the getBytes method.

Cheers,

Hendrik

like image 184
holtmann Avatar answered Oct 17 '22 08:10

holtmann


If you already have your ALAsset, you should be able to get an NSData of the default representation using the following:

NSData *data = [NSData dataWithContentsOfURL:[[asset defaultRepresentation] url]];
like image 21
highlycaffeinated Avatar answered Oct 17 '22 06:10

highlycaffeinated