Programmatically save image by specifying name in ios [duplicate] - iphone

How can I save an image (like using UIImageWriteToSavedPhotosAlbum() method) with a filename of my choice to the private/var folder?

Kenny, you had the answer! For illustration I always think code is more helpful.
//I do this in the didFinishPickingImage:(UIImage *)img method
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
//save to the default 100Apple(Camera Roll) folder.
[imageData writeToFile:#"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO];

UIImageWriteToSavedPhotosAlbum() is only used for saving to the photos camera roll. To save to a custom folder, you need to convert the UIImage into NSData with UIImageJPEGRepresentation() or UIImagePNGRepresentation(), then save this NSData to anywhere you like.

You can use below code, without use of ALAssetsLibrary...
NSString *fileName;
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
{
UIImageWriteToSavedPhotosAlbum(image,nil, nil, nil);
[self performSelector:#selector(GetImageName) withObject:nil afterDelay:0.5];
}
else
{
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
fileName = [[result firstObject] filename];
}
}];
-(void)GetImageName
{
NSString *str =#"";
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
str = [[fetchResult lastObject] filename];
}
fileName = str;
}

Related

Raw image data from camera

I've been searching this forum up and down but I couldn't find what I really need. I want to get raw image data from the camera. Up till now I tried to get the data out of the imageDataSampleBuffer from that method captureStillImageAsynchronouslyFromConnection:completionHandler: and to write it to an NSData object, but that didn't work.
Maybe I'm on the wrong track or maybe I'm just doing it wrong.
What I don't want is for the image to be compressed in any way.
The easy way is to use jpegStillImageNSDataRepresentation: from AVCaptureStillImageOutput, but like I said I don't want it to be compressed.
Thanks!
This is how i do it:
1: I first open the camera using:
- (void)openCamera
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
(NSString *) kUTTypeMovie, nil];
imagePicker.allowsEditing = NO;
[self presentModalViewController:imagePicker animated:YES];
}
else {
lblError.text = NSLocalizedStringFromTable(#"noCameraFound", #"Errors", #"");
}
}
When the picture is taken this method gets called:
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Save and get the path of the image
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
// Save the image
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if(!error) {
//Save path and location to database
NSString *pathLocation = [[NSString alloc] initWithFormat:#"%#", assetURL];
} else {
NSLog(#"CameraViewController: Error on saving image : %# {imagePickerController}", error);
}
}];
}
[imagePicker dismissModalViewControllerAnimated:YES];
}
Then with that path i get the picture from the library in FULL resolution (using the "1"):
-(void)preparePicture: (NSString *) filePathPicture{
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *myasset)
{
if(myasset != nil){
ALAssetRepresentation *assetRep = [myasset defaultRepresentation];
CGImageRef imageRef = [assetRep fullResolutionImage];
if (imageRef) {
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 1);
}
}else {
//error
}
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error)
{
NSString *errorString = [NSString stringWithFormat:#"can't get image, %#",[error localizedDescription]];
NSLog(#"%#", errorString);
};
if(filePathPicture && [filePathPicture length])
{
NSURL *assetUrl = [NSURL URLWithString:filePathPicture];
ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetUrl
resultBlock:resultBlock
failureBlock:failureBlock];
}
}
Hope this helps you a bit further :-).

MPMoviePlayerController with no content (iOS 5) - The Operation Could Not Be Completed

I have problem with MPMoviePlayerController (self.mp). When I want to access duration property, I get 0, when I want to access thumbnail…, I get nil. On iOS 4 it is OK, iOS 5 it is not.
After all app says to me: The Operation Could Not Be Completed.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeMovie]){
NSString *tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
double hashToNameOfFile = [NSDate timeIntervalSinceReferenceDate] * 1000.0;
NSString *finalPath = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"%.0f.%#", hashToNameOfFile, #"MOV"]];
NSString *finalPathToThumbRetina = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"thumb_%.0f#2x.%#", hashToNameOfFile, #"jpg"]];
NSString *finalPathToThumb = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"thumb_%.0f.%#", hashToNameOfFile, #"jpg"]];
// we do need retina now, we use real name for CoreData
NSString *finalImage = [finalPath lastPathComponent];
NSString *finalImageThumb = [finalPathToThumb lastPathComponent];
if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(tempFilePath)){
// Copy it to the camera roll.
UISaveVideoAtPathToSavedPhotosAlbum(tempFilePath, self, #selector(video:didFinishSavingWithError:contextInfo:), tempFilePath);
}
// save video to application directory
NSData *videoData = [NSData dataWithContentsOfFile:tempFilePath];
if ( [videoData writeToFile:finalPath atomically:YES] ) {
NSLog(#"SAVED");
}
else{
NSLog(#"NOT SAVED");
}
// create thumbnail of video
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:finalPath]];
self.mp = moviePlayer;
[moviePlayer release];
NSData *videoData2 = [NSData dataWithContentsOfFile:finalPath];
NSLog(#"LENGTH %i", [videoData2 length]);
NSLog(#"FINAL PATH %#", finalPath);
UIImage *image = [[[UIImage alloc] init] autorelease];
image = [self.mp thumbnailImageAtTime:(NSTimeInterval)1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
NSLog(#"%#", [image size]);
UIImage *thumbImageRetina = [image thumbnailImage:400 transparentBorder:0 cornerRadius:0 interpolationQuality:kCGInterpolationDefault];
UIImage *thumbImage = [image thumbnailImage:200 transparentBorder:0 cornerRadius:0 interpolationQuality:kCGInterpolationDefault];
NSData *thumbImageRetinaData = [NSData dataWithData:UIImageJPEGRepresentation(thumbImageRetina, 1.0)];
NSData *thumbImageData = [NSData dataWithData:UIImageJPEGRepresentation(thumbImage, 1.0)];
if ( [thumbImageRetinaData writeToFile:finalPathToThumbRetina atomically:YES] ) {
NSLog(#"RETINA THUMB SAVED");
}
else{
NSLog(#"RETINA THUMB NOT SAVED");
}
if ( [thumbImageData writeToFile:finalPathToThumb atomically:YES] ) {
NSLog(#"THUMB SAVED");
}
else{
NSLog(#"THUMB NOT SAVED");
}
// duration of video
double dur = [self.mp duration];
NSLog(#"DUR %f", dur);
TaleRecords *newTaleRecord = (TaleRecords *)[NSEntityDescription insertNewObjectForEntityForName:#"TaleRecords" inManagedObjectContext:_context];
newTaleRecord.content = finalImage;
newTaleRecord.date = [NSDate date];
NSDecimalNumber *latNum = [[NSDecimalNumber alloc] initWithDouble:[self.latitude doubleValue]];
NSDecimalNumber *longNum = [[NSDecimalNumber alloc] initWithDouble:[self.longitude doubleValue]];
newTaleRecord.latitude = latNum; // vertical
newTaleRecord.longitude = longNum; // horizontal
[latNum release];
[longNum release];
newTaleRecord.contentType = [[NSString alloc] initWithFormat:#"cTypeVideo"];
newTaleRecord.thumb = finalImageThumb;
newTaleRecord.duration = [NSNumber numberWithDouble:dur];
newTaleRecord.tale = tales;
tales.record = [newTaleRecord tale].record;
NSError *error = nil;
if (![_context save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
[CLController.locationManager stopUpdatingLocation];
[self dismissModalViewControllerAnimated:YES];
}
More simple example
I am doing this:
// save video to application directory
NSData *videoData = [NSData dataWithContentsOfFile:tempFilePath];
if ( [videoData writeToFile:finalPath atomically:YES] ) {
NSLog(#"SAVED");
}
else{
NSLog(#"NOT SAVED");
}
At tempFilePath is real video content and I write it to finalPath. After that I create MPMoviePlayerController instance:
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:finalPath]];
self.mp = moviePlayer;
[moviePlayer release];
But self.mp give me no content. When I want to do [self.mp duration], it returns zero/nil. Path to resource works, but it seems no content is there.
Thank you for your help.
I figured out my problem.
It is like iOS5 is not comfortable with:
NSString *tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
so instead, if you just use
NSURL *someUrl =[info objectForKey:UIImagePickerControllerMediaURL] ;
and then initial mpmovieplayercontroller with this url, it works fine for me,
which is exactly the opposite of iOS4.
here is my code:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"%#",mediaURL);
if (!mymoviePlayer) {
mymoviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:mediaURL];
[mymoviePlayer setControlStyle:MPMovieControlStyleNone];
[mymoviePlayer.view setFrame: videoView.bounds];
[videoView addSubview:mymoviePlayer.view];
}
else
{
[mymoviePlayer setContentURL:mediaURL];
[mymoviePlayer stop];
[mymoviePlayer setInitialPlaybackTime:-1];
}
[self dismissModalViewControllerAnimated:YES];
}

uiimagepickercontroller - get the name of the image selected from photo library

I am trying to upload the image from my iPhone/iPod touch to my online repository, I have successfully picked the image from Photo Album but i am facing one problem i want to know the name of the image such as image1.jpg or some thing like that. How i would know the name of the picked image.
Instead of using the usual image picker method (UIImage*)[info valueForKey:UIImagePickerOriginalImage] which gives you the selected image as an instance of UIImage, you can use the AssetsLibrary.framework and export the actual source file (including format, name and all metadata). This also has the advantage of the original file format (png or jpg) being preserved.
#import <AssetsLibrary/AssetsLibrary.h>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissPicker];
// try to get media resource (in case of a video)
NSURL *resourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
if(resourceURL) {
// it's a video: handle import
[self doSomethingWith:resourceURL];
} else {
// it's a photo
resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary *assetLibrary = [ALAssetsLibrary new];
[assetLibrary assetForURL:resourceURL
resultBlock:^(ALAsset *asset) {
// get data
ALAssetRepresentation *assetRep = [asset defaultRepresentation];
CGImageRef cgImg = [assetRep fullResolutionImage];
NSString *filename = [assetRep filename];
UIImage *img = [UIImage imageWithCGImage:cgImg];
NSData *data = UIImagePNGRepresentation(img);
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSURL *tempFileURL = [NSURL fileURLWithPath:[cacheDir stringByAppendingPathComponent:filename]];
BOOL result = [data writeToFile:tempFileURL.path atomically:YES];
if(result) {
// handle import
[self doSomethingWith:resourceURL];
// remove temp file
result = [[NSFileManager defaultManager] removeItemAtURL:tempFileURL error:nil];
if(!result) { NSLog(#"Error removing temp file %#", tempFileURL); }
}
}
failureBlock:^(NSError *error) {
NSLog(#"%#", error);
}];
return;
}
}
I guess knowing the exact image name would not be an issue rather getting a unique name for the picked image would solve your purpose so that you can upload the image on server and track it via its name. May be this can help you
NSMutableString *imageName = [[[NSMutableString alloc] initWithCapacity:0] autorelease];
CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
if (theUUID) {
[imageName appendString:NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID))];
CFRelease(theUUID);
}
[imageName appendString:#".png"];
After you pick the image from Picker you can generate a unique name and assign it to the Picked image.
Cheers

To save recorded video

Please can anyone provide any sample code to save video after recording.
I m able to record video using UIImagePickerController.
if (canShootVideo) {
UIImagePickerController *videoRecorder = [[UIImagePickerController alloc] init];
videoRecorder.sourceType = UIImagePickerControllerSourceTypeCamera;
videoRecorder.delegate = self;
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(SELF contains %#)", #"movie"]];
BOOL movieOutputPossible = (videoMediaTypesOnly != nil);
if (movieOutputPossible) {
videoRecorder.mediaTypes = videoMediaTypesOnly;
[self presentModalViewController:videoRecorder animated:YES];
}
[videoRecorder release];
}
but how to save it. Can anyone please tell.
Thanks in advance
- (void)saveVideo:(NSURL *)videoUrl {
NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
[videoData writeToFile:#"YOUR_PATH_HERE" atomically:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *type = [mediaDict objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] ||
[type isEqualToString:(NSString *)kUTTypeMovie]) { // movie != video
NSURL *videoURL [mediaDict objectForKey:UIImagePickerControllerMediaURL];
[self saveVideo:videoUrl];
}
}
This is for the case you want to save the video into some file path that you can control. You can save into "Saved Photos" as well

UIImage Saving image with file name on the iPhone

How can I save an image (like using UIImageWriteToSavedPhotosAlbum() method) with a filename of my choice to the private/var folder?
Kenny, you had the answer! For illustration I always think code is more helpful.
//I do this in the didFinishPickingImage:(UIImage *)img method
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
//save to the default 100Apple(Camera Roll) folder.
[imageData writeToFile:#"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO];
UIImageWriteToSavedPhotosAlbum() is only used for saving to the photos camera roll. To save to a custom folder, you need to convert the UIImage into NSData with UIImageJPEGRepresentation() or UIImagePNGRepresentation(), then save this NSData to anywhere you like.
You can use below code, without use of ALAssetsLibrary...
NSString *fileName;
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
{
UIImageWriteToSavedPhotosAlbum(image,nil, nil, nil);
[self performSelector:#selector(GetImageName) withObject:nil afterDelay:0.5];
}
else
{
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
fileName = [[result firstObject] filename];
}
}];
-(void)GetImageName
{
NSString *str =#"";
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
str = [[fetchResult lastObject] filename];
}
fileName = str;
}