Im having NSData of Image type HEIC (photo taken from IOS 12), I need to convert HEIC to JPG and then add to Photo library(to phone having IOS 10.3). Since IOS 10.3 doesn't support of HEIC photo type i need to convert and add to library.
I have tried the following code but failed to add into library.
for converting i used.
UIImageJPEGRepresentation([UIImage imageWithData:imageData], 0.7);
as suggested in other threads. But when i add the resulted data to Photo library i am getting error as Error Domain=NSCocoaErrorDomain Code=-1 "(null)".
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:imageData options:nil];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
[weakSelf writeLog:[NSString stringWithFormat:#"Error on adding photo to photo album: %#",error.debugDescription]];
}
dispatch_semaphore_signal(weakSelf.savephoto);
}];
Related
In iOS 10 I start to replace asset-library to PhotoKit to manage image picker. But there is an issue.
The specific step is that app needs system camera and user shot a photo after that the delegate method imagePickerController:didFinishPickingMediaWithInfo: will be called.
Then, here is my code:
UIImage *pickerImage = [[info objectForKey:UIImagePickerControllerOriginalImage] fixOrientation];
PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
__block NSString *localId;
[photoLibrary performChanges:^{
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:pickerImage];
localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (success) {
// to get localIdentifier and reload collectionView
}
}];
line 1 that fixOrientation is a custom category that return UIImage instance.
Only call [PHAssetChangeRequest creationRequestForAssetFromImage:] method performs fine. However, when I want to fetch newly created photo to use [assetChangeRequest placeholderForCreatedAsset] , it shows memory leak and app crash.
Above all, any solution to fetch created photo just moment or other methods to solve that by using Photos Framework?
I used to save a photo to the camera roll using ALAssetLibrary's writeImageToSavedPhotosAlbum:metadata:completionBlock, but that is now deprecated in iOS 9.0, so I switched to PHPhotoLibrary's version which looks like
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
}completionHandler:^(BOOL success, NSError *error) {
if (success){
NSLog(#"Image Saved!");
} else {
NSLog(#"Error: %#", error);
}
}];
This saves the image itself, but loses the metadata (exif ect) and I can't find any fixes of how to preserve this data when I save the photo. Any help would be appreciated. TYIA
I think the method
creationRequestForAssetFromImage:(UIImage *)image;
saves only image data. It doesn't include metadata.
If you want to save a image with metadata, you can do it by the following step.
First Save your image in temporary folder and get its path as NSURL.
Then Call the method
creationRequestForAssetFromImageAtFileURL:(NSURL *)fileURL;
with the NSURL you get in First step.
I create an image at url provided by PHContentEditingOutput. When I load data to UIImage and save it like this - it works.
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
NSData *data = [NSData dataWithContentsOfURL:contentEditingOutput.renderedContentURL]
UIImage *image = [UIImage imageWithData:data];
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError *error) {
...
}];
But when I try approach with url it fails:
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:contentEditingOutput.renderedContentURL];
} completionHandler:^(BOOL success, NSError *error) {
...
}];
Error:
Error Domain=NSCocoaErrorDomain Code=-1 "The operation couldn’t be completed. (Cocoa error -1.)"
UPDATE:
The same error when I try to save a modification.
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *request = [PHAssetChangeRequest changeRequestForAsset:asset];
request.contentEditingOutput = contentEditingOutput;
} completionHandler:^(BOOL success, NSError *error) {
...
}];
The method works for a video (creationRequestForAssetFromVideoAtFileURL:), but not for an image. What went wrong?
The problem is in the file format. I was trying to edit PNG screenshot, but renderingContentURL was always tmp/filename.JPG. At first I thought it was a bug, but according to the documentation this is correct behaviour.
renderedContentURL
Read this property to find a URL for writing edited asset content. Then, if editing a photo asset, write the altered photo image to a file in JPEG format at this URL. If editing a video asset, export the video to a QuickTime (.mov) file at this URL.
The solution is to convert the image with function
NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);
When passing the metadata, I also had the issue consistently showing whenever the Orientation (inside the image metadata) was anything other than CGImagePropertyOrientationUp.
This is also stated inside the renderedContentURL documentation:
Edited asset content must incorporate (or “bake in”) the intended
orientation of the asset. That is, the orientation metadata (if any)
that you write in the output image or video file must declare the “up”
orientation, and the image or video data must appear right-side up
when presented without orientation metadata.
For images, the following metadata keys need to be updated (while the image data is also rotated):
• kCGImagePropertyTIFFDictionary \ kCGImagePropertyTIFFOrientation
• kCGImagePropertyOrientation
• possibly, kCGImagePropertyIPTCImageOrientation
I downloaded an gif image from the network using AFNetworking 2.0 then save it to camera roll using ALAssetsLibrary
[assetsLibrary writeImageToSavedPhotosAlbum:[responseObject CGImage] orientation:(ALAssetOrientation)[responseObject imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error)
{
if (error)
{
[App showAlertWithTitle:#"Error" message:#"Save message failed"];
}
else
{
[App showAlertWithTitle:#"Success" message:#"Saved success"];
}
}];
Then I tried to retrieve this image from camera using UIImagePickerViewController, but the image I retrieved was not a GIF image but a jpeg image with reference url:
UIImagePickerControllerReferenceURL = "assets-library://asset/asset.JPG?id=2E7C87E4-5853-4946-B86B-CC8AAF094307&ext=JPG";
I don't know whether the fault is ALAssetsLibrary or UIImagePickerViewController and how to surpass it
The photo library does not support GIFs.
It has support for PHAssetMediaTypeImage (a JPG), PHAssetMediaTypeVideo (a MOV), or PHAssetMediaTypeAudio (probably an M4A, not sure here).
https://developer.apple.com/library/ios/documentation/Photos/Reference/Photos_Constants/index.html#//apple_ref/c/tdef/PHAssetMediaSubtype
The writeImageToSavedPhotosAlbum: methods only save still images as JPEGs, as do the new Photos methods. However, there are ways of saving other formats, including (yes!) GIF.
You don't need to mess about with CGImageRefs—just grab the GIF data and then save it, using the writeImageDataToSavedPhotosAlbum:metadata:completionBlock: method. Something like this:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSData *data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://somewhere/something.gif"]]];
[library writeImageDataToSavedPhotosAlbum:data
metadata:nil
completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
[App showAlertWithTitle:#"Error" message:#"Save message failed"];
} else {
[App showAlertWithTitle:#"Success" message:#"Saved success"];
}
}];
See this answer.
If you want to generate a GIF, it's somewhat more complex, but simply saving one is straightforward.
Hey I'm new to iPhone and I have been trying to make an gallery kind of app. Basically, what I want to do is that i need to save all the captured images into a specific folder like a new album "My_App Images" related to our app name in iPhone device gallery, it's working for me, but I am having trouble to change the image file name, i don't know that Is it possible to specify a file name? Using iPhoto, currently i am getting image file name as "IMG_0094.jpg", can we change it with any other file name like "Anyfilename.png" format programmatically?
here is my code for saving images to the specific album :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self.library saveImage:image toAlbum:#"My_App Images" withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(#"Image saving error: %#", [error description]);
}
}];
[picker dismissViewControllerAnimated:NO completion:nil];
}
Any source or link for reference is appreciated. Thanks for the help!
There is a way to kinda do that, by setting the image IPTC metadata field "Object Name". If you later import the image to iPhoto, then this name will be used as its title.
See details (and code) at http://ootips.org/yonat/how-to-set-the-image-name-when-saving-to-the-camera-roll/ .
Do you meant,
// Build NSData in memory from the btnImage...
NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
// Save to the default Apple (Camera Roll) folder.
[imageData writeToFile:#"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO];
Now adjust the path of folder as per your folder name...
Sorry to disappoint you, but it seems that you can not change the name of the photos, before or after saving, in the photo album, custom or not. Here is a post to explain it:
iOS rename/delete albums of photos
Edit
So, to clarify my comment, use the following override:
Download the NSMutableDictionary category for metadata of image here.
Also download the sample project CustomAlbumDemo from here and modify the NSMutableDictionary+ImageMetadata.m file in the CustomAlbumDemo project as:
-(void)saveImage:(UIImage*)image toAlbum:(NSString*)albumName withCompletionBlock:(SaveImageCompletion)completionBlock
{
//write the image data to the assets library (camera roll)
NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
NSMutableDictionary *metadata = [[NSMutableDictionary alloc] init];
[metadata setDescription:#"This is my special image"];
[self writeImageDataToSavedPhotosAlbum:imageData metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
//error handling
if (error!=nil) {
completionBlock(error);
return;
}
//add the asset to the custom photo album
[self addAssetURL: assetURL
toAlbum:albumName
withCompletionBlock:completionBlock];
}];
}