UIImagePickerController - Save and Load Image? - iphone

There seems to be a scatter of info on this topic, but it seems rather a muddle, so I hoe you don't mind me asking.
I have a UIImagePickerController working, letting me either take a photo or pick on from the library and then set a UIImageView of my choice to show that image taken/selected.
However, how can I firstly save the image, then load it back in when the application is reopened? Also, I will be saving multiple images so they need to be uniquely identified.
Any help will be massively appreciated, thanks.

I don't know of a way to get the Photo from the Photo Album a Second time. There does not seem to be a way to retrieve it again. We do a few things to save the Image internally.
We either convert the Image to NSData and save it in CoreData, or we save it off to our sandbox.
here is a snip of code that we use, this is doing one of a few things, I'm getting the Image from a ScreenShot, though its the same once you have the UIImage.
// go get our screenshot
UIImage* screenShot = [self createScreenShotThumbnailWithWidth:200];
// Save screen shot as a png in the documents directory with the UUID of the IoCDScreen
// Saving to Sandbox
[self saveImage:screenShot withName:currentScreen.itemUUID];
// save image to Photo Album - though you can't get a ref back to it
UIImageWriteToSavedPhotosAlbum(screenShot, self, nil, nil);
//convert our screen shot PNG to NSData and store it in a CoreData Managed Object
currentScreen.screenImageDevelopment = [NSData dataWithData: UIImagePNGRepresentation( screenShot )];
Helper Functions used above
//--------------------------------------------------------------------------------------------------------
// saveImage:withName:
// Description: Save the Image with the name to the Documents folder
//
//--------------------------------------------------------------------------------------------------------
- (void)saveImage:(UIImage *)image withName:(NSString *)name {
//grab the data from our image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//get a path to the documents Directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Add out name to the end of the path with .PNG
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", name]];
//Save the file, over write existing if exists.
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}
//--------------------------------------------------------------------------------------------------------
// createScreenShotThumbnailWithWidth
// Description: Grab a screen shot and then scale it to the width supplied
//
//--------------------------------------------------------------------------------------------------------
-(UIImage *) createScreenShotThumbnailWithWidth:(CGFloat)width{
// Size of our View
CGSize size = self.view.bounds.size;
//First Grab our Screen Shot at Full Resolution
UIGraphicsBeginImageContext(size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Calculate the scal ratio of the image with the width supplied.
CGFloat ratio = 0;
if (size.width > size.height) {
ratio = width / size.width;
} else {
ratio = width / size.height;
}
//Setup our rect to draw the Screen shot into
CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);
//Scale the screenshot and save it back into itself
UIGraphicsBeginImageContext(rect.size);
[screenShot drawInRect:rect];
screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Send back our screen shot
return screenShot;
}

Related

How to reduce the image resolution and memory size when saving or while capturing an image in iphone

In my contacts application i used an image view to display the contact persons image,
in this process while saving the data user can save the contact person image as well (in the form of string, image file name).
I copy the images in sand box (Documents directory) and save the file names of images
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
NSString *DirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[[NSUserDefaults standardUserDefaults] setValue:storedPicsDict.contactImage forKey:#"oldContactPic"];
//To SET the NEw IMAGE images from directory path
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef generatedUUIDString = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
NSString* hashKey = [(NSString*)generatedUUIDString autorelease];
self.ContactImageFilePath = [NSString stringWithFormat:#"%#/%#.png",DirectoryPath,hashKey];
storedPicsDict.contactImage = self.ContactImageFilePath;
[contactPicture setImage:image forState:UIControlStateNormal];
isNewContactImage = true;
}
[picker dismissModalViewControllerAnimated:YES];
}
the respective save image will displayed in contact's information.
But w*hen i saved few more images more than 6/7 it causes memory warnings and the and app gets crashed/slow down.*
So i need to save images with LOW RESOUTION and LOW MEMORY SIZE,
How is it possilbe, thanks
1>Save the image in jpeg format so that image size gets reduced
NSData *imgData = UIImageJPEGRepresentation(your_UIImage_to_save, 0.5);
[imgData writeToFile:path_of_doc_dir_with_image_name atomically:YES];
2>
If you want to reduce the quality and size of the image you can use this code
CGSize newSize=CGSizeMake(50,50); // I am giving resolution 50*50 , you can change your need
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Hope this will help you..
how about using this
UIImage *small = [UIImage imageWithCGImage:original.CGImage scale:0.25 orientation:original.imageOrientation];
and save the smaller image to a tmp file path for uploading. Do the images need to be .png?
Otherwise, you may also try UIImageJPEGRepresentation to lower the image's quality.

How to save a scaled uiimage

the screen image link,the savePic image link,You can find the different between screenImg and savePic.
I set the backgroundImageView a very small png. and i want save the backgroundimageview to a Picture。
In the iPhone Simulator Screen, the edge of image is normal, but the edge of savePic is not clear. Anybody can tell me how to save a high definition picture.
- (void)viewDidLoad
{
[super viewDidLoad];
//_backImgView 320*480
self.backImgView.image = [UIImage imageNamed:#"Purple.png"];
[self performSelector:#selector(savePic) withObject:nil afterDelay:0.1];
}
- (void)savePic
{
BOOL isDir;
NSString *dirPath = [NSHomeDirectory() stringByAppendingPathComponent:#"/Documents/Pic"];
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:dirPath isDirectory:&isDir]){
BOOL bo = [fm createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
if(!bo){
NSLog(#"-->Create CardSlide Dir Fail!!!");
return;
}
}
UIGraphicsBeginImageContext(_backImgView.bounds.size);
//UIGraphicsBeginImageContextWithOptions(_backImgView.bounds.size, _backImgView.opaque, 2.0);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
[_backImgView drawRect:_backImgView.bounds];
//[_backImgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *bgImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString *path = [NSString stringWithFormat:#"save_%#.jpg", #"demo"];
NSString *jpgPath = [dirPath stringByAppendingPathComponent:path];
BOOL isSucc = [UIImageJPEGRepresentation(bgImg, 1.0) writeToFile:jpgPath atomically:YES];
NSLog(#"%# write photo %#!", jpgPath, isSucc?#"SUCC":#"FAIL");
}
Using a small image, is impossible to scale it the correct way to a bigger image, you will always go through blurry, noisy images BUT if you image could have stretchable repetitive parts, you can stretch the interior of the image without creating a new one. There are two API in UIImage called:
– resizableImageWithCapInsets: (Only ios5)
– stretchableImageWithLeftCapWidth:topCapHeight: (Deprecated in iOS 5.0)
If you find the correct inset you can avoid to create a new image, basically is the same system used to create the bubble in message application. The balloon is really small but it has a stretchable area that maintain the aspect ratio.
Since the image is really simple you could also think to draw it using Quartz functions creating a rect path, paths are "almost" res independent just need to scale them the correct size.

Take a screenshot of screen

I need to take a screen shot of a screen and save as pdf. I have accomplished the save as pdf task however the screenshot i take always gives a blank pdf. I have no idea why. My code is as follows :
-(IBAction)takeScreenShot
{
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIImageView *newImage = [[UIImageView alloc] initWithImage:image];
UIGraphicsEndImageContext();
[self createPDFfromUIView:newImage saveToDocumentsWithFileName:#"SecondScreen1.pdf"];
}
-(void)createPDFfromUIView:(UIImageView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
//CGSize pageSize = CGSizeMake(612, 792);
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
//[aView.layer renderInContext:UIGraphicsGetCurrentContext()];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
}
This line that's commented out should be writing your image to the pdf. Put that code back in and it might work.
[aView.layer renderInContext:UIGraphicsGetCurrentContext()];
If that's failing (with no errors) make sure that UIImage *image is not blank.

Convert Screenshot to PDF in Xcode?

How might one convert a screenshot, taken on an iPhone for example, into a PDF file. It's easy enough to take the screenshot and put it into a UIImage, but it's the conversion which has me stumped. I took a look at the Quartz framework which is the only one in Xcode that I know to support the PDF format, but couldn't find anything there to make this work. Is there anything native to Xcode that I'm missing? If not, is there a public framework somewhere that could handle a conversion like this?
I figured it out. It involved saving a screenshot as a UIImage, and then using the very helpful tutorial found here to get me going with the PDF conversion. As it turns out, there are functions to handle the making of PDF documents in the Core Graphics class.
You wouldn't convert a screenshot to a pdf. You would create a screenshot, create a pdf and insert the screenshot image into the first page of the pdf.
Untested code to create image:
nameStr = [NSString stringWithFormat:#"myImage.png"];
fileManager = [NSFileManager defaultManager];
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
namePath = [documentsDirectory stringByAppendingString:#"/"];
namePath = [thumbnailPath nameStr];
CGRect contextRect = CGRectMake(0, 0, 1024, 768);
UIGraphicsBeginImageContext(contextRect.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(viewImage);
UIImage *myImage = [[UIImage alloc] initWithData:data];
Untested code to add image to a pdf:
pageSize = CGSizeMake(1024, 768);
fileName = #"myFile.pdf";
pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
[myImage drawInRect:CGRectMake( 0, 0, 1024, 768];
UIGraphicsEndPDFContext();
p.s. assuming ipad 1024 x 768 above

How to adjust a image size after using UIImagePickerController take a photo?

How to resize a image when save photo in document folder ???
This is how I save an image in iphone.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageFile = nil;
NSString *name_png = [NSString stringWithFormat:#"%#.png",photoName];
imageFile = [documentsDirectory stringByAppendingPathComponent:name_png];
[UIImagePNGRepresentation(self.theImageView.image) writeToFile:imageFile atomically:YES];
How to resize it from original size to 200 X 200 pixels?
Or can I load the image file than resize it?
Actually, I was create a cover flow with many images, and the image was from camera.
I can find a cover flow sample, but when I load image, it full of iphone screen.
Not a small cover image.
UIImage resize : Go thru this link.
Thanks to Paul Lynch.
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}