I can upload a photo into ui image viewer from camera roll but when I restart my app or go to another page and come back, the uploaded photo disappears. How do I keep them?
- (IBAction)selectImage:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
UIImage *chosenImage = selectedImage;
self.homeImage.image = chosenImage;
[self.view setNeedsDisplay];
[picker dismissViewControllerAnimated:YES completion:NULL];
NSData *imageData = UIImagePNGRepresentation(chosenImage.images);
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];
}
I expect the second method to keep the image in the internal database and keep showing my uploaded image, but it doesn't.
You need to load the image from file and assign it to your view after view is created, something similar to:
- (void)viewDidLoad {
NSString * imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/myImage.png"];
self.homeImage.image = [UIImage imageWithContentsOfFile:imagePath];
}
Related
I am developing a chat, in chat I need to share pictures, my app has a button to select an image from gallery.
This is my button code:
[upBtn2 addTarget:self action:#selector(uploadImage:) forControlEvents:UIControlEventTouchUpInside];
In gallery the user can select an image to share in chat with someone else, the conversation is just 1 to 1 chat.
This is my code.
- (IBAction)uploadImage:(id)sender
{
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
newMedia = NO;
}
}
-(void)imagePickerControllerDidCancel:
(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
Uploadedimage.image=image;
if (newMedia)
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
// [self performSelector:#selector(uploadToServer) withObject:nil afterDelay:0.0];
XMPPMessage *message = [[XMPPMessage alloc] initWithType:XMPP_MESSAGE_TYPE_CHAT to:[self.contact jid]];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *imageStr = [GTMBase64 stringByEncodingData:imageData];
//decoding
NSData *imageData2 = [GTMBase64 decodeString:imageStr];
[message addBody:imageStr];
[[[AppDelegate appDelegate] xmppStream] sendElement:message];
XMPPJID *myJID = [[[AppDelegate appDelegate] xmppStream] myJID];
[self addMessage:#{
XMPP_TIMESTAMP: [NSDate date],
XMPP_MESSAGE_USERNAME: [myJID bare],
XMPP_MESSAGE_TEXT: imageStr,
}];
[self.tableView reloadData];
[self scrollToBottom:true];
}
- (void)image:(UIImage *)image
finishedSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Archivo guardado"
message: #"Error al guardar archivo"\
delegate: nil
cancelButtonTitle:#"Aceptar"
otherButtonTitles:nil];
[alert show];
}
}
I am getting an issue, the code it is showing
2014-10-14 11:01:21.973 Ucity[2907:60b] messages: (
{
text = "/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAE9KADAAQAAAABAAAFcAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/..."
I need to see the image there but for some reason its showing that text.
I am using GTMBase 64 library
#import "GTMBase64.h"
Can someone help me to fix this problem?
That cryptic text is the image. It's just the base-64 string representation of the image. I assume you're doing this base-64 encoding for a reason (e.g. this format is required by some service to which you are uploading the image).
I'm presuming from your question that you want to show the image somewhere. I'm just trying to reconcile this with this code, in which you retrieved the image, converted it to a base-64 string, then discarded the original image, and now you're asking us why you're only seeing the string.
If you need the image again, there are a couple of options:
Keep the UIImage (or the NSData) that you grabbed in didFinishPickingMediaWithInfo.
You could alternatively convert the base-64 string back to a NSData (and then create a UIImage from that). This is a pretty convoluted approach, but it would work.
As an aside, if you wanted, you could probably replace GTMBase64.h with the native base-64 methods that Apple exposed in iOS 7. See https://stackoverflow.com/a/19794564/1271826.
Also, I don't personally like grabbing the UIImage and doing the PNG conversion to get the NSData. I always grab the original asset as shown here. This ensures there's no loss of information and that the resulting NSData isn't larger than it needs to be.
I've made an app for iPhone which is Flappy Bird-inspired. This app is made just so I can learn the programming behind app-making, and hopefully make an more original and advanced app soon.
The app can load a picture taken either from your Photo Library, or from your iPhone-Camera. I used this code:
- (IBAction)didTapPhoto:(UITapGestureRecognizer *)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Take a Photo", #"Use Photo Library", nil];
[actionSheet showInView:self.view];
}
-(void) pickPhotoFromLibrary {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self.navigationController presentViewController:self.imagePicker animated:YES completion:nil];
}
-(void) takePhotoWithCamera {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self.navigationController presentViewController:self.imagePicker animated:YES completion:nil];
}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == actionSheet.cancelButtonIndex)return;
switch (buttonIndex) {
case 0:
[self takePhotoWithCamera];
break;
case 1:
[self pickPhotoFromLibrary];
default:
break;
}
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = info[UIImagePickerControllerOriginalImage];
self.imageView.image = image;
}
The question is: How do I save the picture which is loaded in an ImageView, and then load it in another ViewController?
I want the user to take a picture and then use themselves as the flappy bird. I have already made the Flappy Bird course, and used to different flappy birds.
The only issue is that I want it to be possible to save the picture selected by the user as a .png file, just like it was saved in Supporting Files. The picture can be saved as a default, for example #"image1", and in the other ViewController you can set that the ImageView load #"image1".
Save image to iPhone local file:
NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *imageName = [imagePath stringByAppendingPathComponent:#"MainImage.jpg"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
BOOL result = [imageData writeToFile:imageName atomically:YES];
NSLog(#"Saved to %#? %#", imageName, (result? #"YES": #"NO"));
Load the saved image:
NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *imageName = [imagePath stringByAppendingPathComponent:#"MainImage.jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imageName];
I know how to save a picture and this is the code until now. This code shows that the user taps a button and is able to take a photo.
-(IBAction)TakePhoto {
picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:nil];
}
- (IBAction)ChooseExisting {
picker2 = [[UIImagePickerController alloc]init];
picker2.delegate = self;
[picker2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker2 animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageview setImage:image];
//Save Your Image ======
UIImage *yourImage = imageview.image;//imageView.image;
NSString *docDirPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [docDirPath stringByAppendingPathComponent:#"myImageFile.png"];
[UIImagePNGRepresentation(yourImage) writeToFile:filePath atomically:YES];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}
However I want to sort my saved pictures into 6 Category or Genres which the user has to tap using the segment view control. Is this possible to do? I am very new in ios programming and objective-c in xcode and confused with many view controllers however I really like this to work and I a cannot find any resource about this topic. Thanks.
Here is a good demo for saving images to particular album using ALAssetsLibrary:
http://www.touch-code-magazine.com/ios5-saving-photos-in-custom-photo-album-category-for-download/
I hope it will help you out...
or
You can create different libraries using this piece of code:
-(void)createDirectory:(NSString *)directoryName atFilePath:(NSString *)filePath
{
NSString *filePathAndDirectory = [filePath stringByAppendingPathComponent:directoryName];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
And fetch the images through their respective paths!!!
For more information see this: http://kmithi.blogspot.in/2012/08/ios-application-directory-structure.html
I have been searching around for how to do this sporadically for the last few days and havent been able to find anything and hope you can help.
Currently in my app I have 5 diffrent background as part of the project fils and allow the user to chose between them to set the app background to give some customization aspict to the app.
What I am looking to do is allow the user to select a photo that they have saved on thier device and use that as a background for my app but am unable to find out how to do it or perhaps missed it without knowing (I come from a primarraly C# background so still adjusting to termanology and all the fun things that come with learning a know lang and IDE).
What Im looking to do in code is:
User clicks to use thier own image
app opens window to browse through images
user selects image to use
assign and save path (or save image in the app somehow)
set imageview to that image
Thank you everyone for any assistance you can give and the time it takes you to give it. As a FYI Im building for iPhone 5.0
Make a UIImageView in nib file and button and hook the nib
In ViewController.h
#interface ViewController : UIViewController
<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
IBOutlet UIButton *ChooseFileBtn;
}
#property (nonatomic,retain) UIImage *userimage;
-(IBAction)getphoto:(id)sender;
In ViewController.m
-(IBAction)getphoto:(id)sender {
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
userimage = [info objectForKey:UIImagePickerControllerOriginalImage];
imageView.image=userimage;
}
You can use UIImagePickerController to get image from Photo library
-(void)ClickOnsetBG:(id)sender{
UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
imgpicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
imgpicker.delegate=self;
[self.navigationController presentModalViewController:imgpicker animated:YES];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[UIView commitAnimations];
}
Then implement delegate method to get selected image:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *aImgRecord = [info objectForKey:UIImagePickerControllerOriginalImage];
[imgpicker dismissModalViewControllerAnimated:YES];
bgImage.image =aImgRecord;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"custombg.png"];
NSData *imageData = UIImagePNGRepresentation(aImgRecord);
[imageData writeToFile:savedImagePath atomically:NO];
}
This image will be saved in document directory of you app. So when you will reopen your app, you will have to set bgimage from This document directory path.
You can do this with NSUserDefaults also
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
UIImage *newImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *imageData = UIImageJPEGRepresentation(newImage, 1);
[[NSUserDefaults standardUserDefaults] setObject:imageData forKey:#"BackgroundImage"];
[picker dismissViewControllerAnimated:YES completion:^ {
// If you have used UIImageView
[self.yourImageViewObject setImage:newImage];
}];
}
Later the image could be easily shown through NSUserDefaults like
UIImage *image = [UIImage imageWithData:[[NSUserDefaults standardUserDefaults] objectForKey:#"BackgroundImage"]];
I had this working in an old code that I didn’t end up using... now I’m trying it again and it isn’t working. I”m not sure what is wrong. I’d like the user to select an image and then have it available in imageView1 for display. I appreciate the assistance.
- (IBAction)pushPick
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate =self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
//[picker release];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage: (UIImage *)image editingInfo:(NSDictionary *)editingInfo {
[picker.parentViewController dismissModalViewControllerAnimated:YES];
imageView1.image = image;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker.parentViewController dismissModalViewControllerAnimated:YES];
}
Try
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
imageView1.image = image;
[picker release];
[self dismissModalViewControllerAnimated:YES];
}
And make sure the view controller responds to UIImagePickerControllerDelegate.
imagePickerController:didFinishPickingImage:editingInfo: was deprecated in iOS 3.0.
This is how I do this:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
bgImage.image = [info objectForKey:UIImagePickerControllerEditedImage];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(128, 128), YES, 1.0);
[bgImage.image drawInRect:CGRectMake(0,0,128,128)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsFolder = [path objectAtIndex:0];
NSString *tmpPathToFile = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/specificImagedName.jpg", documentsFolder]];
if([imageData writeToFile:tmpPathToFile atomically:YES]){
//NSLog(#"write succesful");
}
///////////////////////////////////////////
[po dismissPopoverAnimated:YES];
[picker release];
[tmpPathToFile release];}
it generates a jpg file to the documents folder of your app. Hope it helps..