Save Image With In App - iphone

What I am needing to do is, take a picture or choose one form the photo library, then save it within the app so that it isn't visible anywhere else but within the app. For example it would be like "My Secret Folder" where images are only seen within the app. I am not making a secret folder app.... So don't worry... =)
I am sorry I don't have much code to show, but I have no idea how to do this.
I was looking at the Rich Text File and was wondering if that was the way to go and if it can even store images, or if I have to do it a different way.
Thanks,
Denali Creative LLC
P.S.
What I am looking to do is save MORE THAN ONE image within the application. So i will need to be able to name what the Image or what ever the image is saved into's file name.

Lookup/Search code for using UIImagePickerController
Convert Image to Data using Convert Image to Data
Save the data to the document folder. No other apps can access your documents folder.
folder, see this post Save Image to Disk
Read data from disk, convert to image and display to reverse process.

You can save the images within your application's Sandbox
The Documents folder is backup during syncs, and Library/Caches folder is not. That gives you a choice between levels of secrecy.
Once you have your image (UIImagePickerController and a class that follows <UIImagePickerControllerDelegate> protocol), convert it to NSData and archive it to your desired folder.
Something like
NSData * imageData = UIImagePNGRepresentation (image);
NSData * imageData = UIImageJPEGRepresentation (image);
when you unarchive the NSData, you can create the image with
[UIImage imageWithData:data];

So u dont want other app to recognize ur images. I am not sure but this might help you. Instead of standard png or jpg extention, just replace a dummy extention like .abc which other apps cant recognize. There might be other ways but I was using this method.

Extract your image from the PhotoPicker info dictionary in the photo picker delegate callback.
Set up a subdirectory somewhere under your /Documents folder, and write the image there.
NSData *pngData = UIImagePNGRepresentation(_myUIImage);
BOOL successFlag = [pngData writeToFile:documentDirectorySubFolder options:0x0 error:&error];

use UIImagePickerController class and implement it delegate
There is a delegate method of image picker view delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info ;
This method is get called when you select the picture from photo Library or take picture from camera.That is good to save your images in core data base then it is only visible with in your app.

I think this idea may be help for you. You can create one app for that like with SQLIte. in which you save your images within your app. but the problem is the images which you save in your app and keep safe from others, you have to manually remove from image gallery

I recommend that you store the images in the Documents Directory and read them from there as it is the most appropriate location to store app content.
Save Image to Documents Directory
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
if ([[extension lowercaseString] isEqualToString:#"png"]) {
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"]) {
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
} else {
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
Load Image From Documents Directory
-(UIImage *)loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}
How-To
//Definitions
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//Save Image to Directory
[self saveImage:imageFromURL withFileName:#"My Image" ofType:#"png" inDirectory:documentsDirectoryPath];
//Load Image From Directory
UIImage * imageFromWeb = [self loadImage:#"My Image" ofType:#"png" inDirectory:documentsDirectoryPath];

Related

File path of image on iPhone

I'm interested in uploading a file (image) from an iPhone library/camera roll to a remote web server. I already have a script working that will upload any file from the phone to a web server. However, I assume that to upload an image from the iPhone, I need the PATH to said image. Is there any way this can be done, once the user picks said image from the camera roll? I.e., how do I get the file path of an image selected in the camera roll?
I have tried to no avail.
Thanks!
You will want to look at the ALAssetsLibrary functions - these let you access photos and videos that are stored in your Photos and Videos libraries on your iOS device.
Specifically, something like:
ALAssetsLibrary *assets = [[ALAssetsLibrary alloc] init];
[assets enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
//the ALAsset should be one of your photos - stick it in an array and after this runs, use it however you need
}
}
failureBlock:^(NSError *error) {
//something went wrong, you can't access the photo gallery
}
];
EDIT
If you are using the UIImagePickerController rather than a purely programatical approach, this simplifies it greatly:
In:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
//you can use UIImagePickerControllerOriginalImage for the original image
//Now, save the image to your apps temp folder,
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:#"upload-image.tmp"];
NSData *imageData = UIImagePNGRepresentation(img);
//you can also use UIImageJPEGRepresentation(img,1); for jpegs
[imageData writeToFile:path atomically:YES];
//now call your method
[someClass uploadMyImageToTheWebFromPath:path];
}

Can i get the name of image from the photos in iPhone

I am using image picker to pick image from gallery in iPhone device. I have to save those images in the same name that is in the gallery. I don want to name it different after picking image. I tried printing the info dictionary after picking image. Its gives image,url and path and type.. but how to get the actual name of the image any idea. Following is what i get in didFinish
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(#"Selected image info: %#",info);
}
this prints
Selected image info : (
{
UIImagePickerControllerMediaType = "public.image";
UIImagePickerControllerOriginalImage = "<UIImage: 0x617d390>";
UIImagePickerControllerReferenceURL = "assets-library://asset/asset.JPG?id=1000000089&ext=JPG";
}
)
my question is any way to get the actual name from the above.
Using the AssetsLibrary framework, you can get the referenceURL from the info dictionary and fetch the asset. Something like this:
NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
__block NSString *fileName = nil;
ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
[library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
fileName = asset.defaultRepresentation.fileName;
} failureBlock:nil];
Images from picked from the gallery, DO NOT have 'names'. You never assign a name to a picture just captured from the camera and even when you add images through iTunes, the original filenames are stripped off and replaced with filenames that iTunes understands for syncing.
These filenames are not meant for programmers to access as they could be replaced by some other images in future syncs.
A good round about for this is to assign the current Date as filenames, while saving to images picked from the gallery. You may save it in your documents or library directory and use a mapping PList file to map images to their filename.
Alternatively, you can also assign unique numbers as filenames and access the images using these values.
Though you mentioned you do not want to assign new names, unfortunately, that's the only way to go about it.
I don't think they have a name. What I did used on my Application, was to save them with a NSDate (current date) as a name.

saving images with UIImagePickerController

I'm trying to save Images the user takes with the camera
1) If I use the UIImageWriteToSavedPhotosAlbum I can't seem to assign the fileName that I want. How, can you choose the file name?
The nice thing about using this option is
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
Then gives a thumbnail gallery of Photo Library directory.
2) which leads me to my next question Can
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; be used to get images from your own personal directory ?
3) Is there anyway to programmatically create sub folders within the Photo Library
4) Lastly,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES);
if (![[NSFileManager defaultManager] fileExistsAtPath:[paths objectAtIndex:0] isDirectory:&isDir]) {
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:[paths objectAtIndex:0 withIntermediateDirectories:YES attributes:nil error:&error];
}
Checking to see if the NSPicturesDirectory exists so I can write to it
I keep getting a Cocoa error 513 not permitted
Thanks in advance
You can't assign a file name to photo library images. ios assign a file name called asset url to the images that are saved to the photo library, we can't change that.
If you need to save the images to photo library you can use ALAssetsLibrary
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation) [image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error)
{
// Eror
}
else
{
// Success
}
}];
[library release];
For more information check:
How to save picture to iPhone photo library?
Save image in UIImageView to iPad Photos Library
1.)
To save a filename of your choice, you need to save the image to your documents directory. This can easily be done like so:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
NSString *current = [NSString stringWithFormat:#"%#/%#",PHOTODATA_PATH,currentItem];
UIGraphicsBeginImageContext(CGSizeMake(160,160));
[image drawInRect:CGRectMake(0,0,160,160)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * thumbSize = UIImageJPEGRepresentation(scaledImage, 1.0);
[thumbSize writeToFile:[NSString stringWithFormat:#"%#_thumb.jpg",current] atomically:YES];
NSData * fullSize = UIImageJPEGRepresentation(image, 1.0);
[fullSize writeToFile:[NSString stringWithFormat:#"%#.jpg",current] atomically:YES];
[self dismissModalViewControllerAnimated:YES];
}
Of course this code may need to be edited to fit your exact situation but gives the basic understanding and way to save a photo to file using NSData.
2.)
Yes, UIImagePickerControllerSourceTypePhotoLibrary will access your Photo Library on your device. Any photos saved or taken from the camera roll will be accessible using this.
3.)
No, you cannot create subfolders in the Photo Library using your application. This can be done using iPhoto or iTunes or the like.
4.)
You only have access to the Documents and Library paths contained within your sandboxed environment. The only way you can save a photo to the Photo Library is by using the appropriate public methods. There is no need to check if the directory exists, the OS will take care of all of the "behind the scenes" tasks it needs to in order to manage the Photo Library.

imageNamed is evil - How to use the function

- (UIImage*)thumbnailImage:(NSString*)fileName
{
UIImage *thumbnail = [thumbnailCache objectForKey:fileName];
if (nil == thumbnail)
{
NSString *thumbnailFile = [NSString stringWithFormat:#"%#/thumbnails/%#.jpg", [[NSBundle mainBundle] resourcePath], fileName];
thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
[thumbnailCache setObject:thumbnail forKey:fileName];
}
return thumbnail;
}
I got this code from http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/ . Can someone tell me how to use this code. I need just a little help how to use this in place of imageNamed.
NSMutableDictionary *thumbnailCache=[[NSMutableDictionary alloc]init];
then add "thumbnails" folder to ur resource folder then put ur png there
- (UIImage*)thumbnailImage:(NSString*)fileName
{
UIImage *thumbnail = [thumbnailCache objectForKey:fileName];
if (nil == thumbnail)
{
NSString *thumbnailFile = [NSString stringWithFormat:#"%#/thumbnails/%#.jpg", [[NSBundle mainBundle] resourcePath], fileName];
thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
[thumbnailCache setObject:thumbnail forKey:fileName];
}
return thumbnail;
}
example
add foo.png to resource folder
//here create UIImageView object then
UIImageviewObject.image=[self thumbnailImage:#"foo.png"];
The code uses a NSMutableDictionary *thumbnailCache to cache UIImage instances. The code assumes that in the app bundle, there's a directory thumbnails with scaled down versions of their images.
The method now first looks in the thumbnailCache dictionary whether the thumbnail for the given image (which is only a filename without full path, e. g. myimage.png). If the dictionary did not contain an image already, the image is loaded from the thumbnails directory (using imageWithContentsOfFile: instead of imageNamed:, since the authors claim the later causes trouble). The loaded image is then stored in the dictionary so the next time the app asks for the thumbnail, it can use the already loaded instance.
For this code to work correctly in your app, you need to add a thumbnails folder to your project. When you add it to your project, be sure to select "Create folder references for any added folders" instead of the default "Create groups for any added folders". Only then you will get a subdirectory in your app's main bundle, otherwise all files are put into the same top-level folder.
But the whole point is that the author claims:
Avoid [UIImage imageNamed:].
Instead, have a NSMutableDictionary.
Look up images in the dictionary.
If found, use that.
If not found, load image using [UIImage imageWithContentsOfFile:] to manually load the image and store it in the dictionary.
thumbnailCache is NSMutableDictionary declared in header file and it should be initialized in .m init method or equivalent method.
If u have the images in the resources (with jpg format, else change the .jpg to .png in the code), then the line should be like
NSString *thumbnailFile = [NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], fileName];
Instead of using
UIImage *thumbImage = [UIImage imageNamed:#"thumb.png"];
UIImage *thumbImage = [self thumbnailImage:#"thumb.png"];

iPhone - file properties

i m creating an application which makes the iphone work as a pendrive for easy file sharing purpose.
In the first stage, i have some files(png, pdf, jpg, zip) in a directory and i made them display in the tableview in the form of mutable array. It displays in the tableView as shown below,
.DS_Store
.localized
gazelle.pdf
Hamburger_sandwich.jpg
IITD TAJ Picture 028_jpg.jpg
iya_logo_final_b&w.jpg
manifesto09-eng.pdf
RSSReader.sql
SimpleURLConnections.zip
SQLTutorial
I just want to display the name of the files and i do not want to display the extensions. I know that it is possible to extract the extensions of a file in NSFileManager. But i do not know how. Please help me to make my table view look like this
.DS_Store
.localized
gazelle
Hamburger_sandwich
IITD TAJ Picture 028_jpg
iya_logo_final_b&w
manifesto09-eng
RSSReader
SimpleURLConnections
SQLTutorial
In the second stage i have a detailedViewController which takes displays the detailed view of the file like
file size
file type
if it is a image, it should open in imageView
if it is a song, it should play it
So i need to retrive the properties like filePath, fileType, fileSize.. of each files. Please guide me with a tutorial if possible. I too do not have any idea how to convert a mutableArray to a NSString and call the methods like stringByDeletingPathExtension. Please help me. I can even send my source code if needed. If possible, guide me with some example codes and tutorial.
This should work:)
This will get all files in a directory in a NSString *parentDirectory, get its size, if image do something otherwise it assumes is a sound file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filePaths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
for (NSString *filePath in filePaths) {
//filename without extension
NSString *fileWithoutExtension = [[filePath lastPathComponent] stringByDeletingPathExtension];
//file size
unsigned long long s = [[fm attributesOfItemAtPath:[parentDirectory stringByAppendingPathComponent:filePath]
error:NULL] fileSize];
UIImage *image = [UIImage imageNamed:[parentDirectory stringByAppendingPathComponent:filePath];];
//if image...
if(image){
//show it here
}
else{
//otherwise it should be music then, play it using AVFoundation or AudioToolBox
}
}
I hope you will have the file name in NSURL object, if so then you can use the following code to get just the file name and can remove the file extension from the string.
NSArray *fileName = [[fileURL lastPathComponent] componentsSeparatedByString:#"."];
NSLog(#"%#",[fileName objectAtIndex:0]);