2011-12-30 130 views
3

所以在我的应用程序中,我希望用户能够选择/拍照,然后在UIImageView中显示该图像。问题是,通过我的研究,我发现了很多方法来保存/加载图像,但显然在知道图像是.png还是.jpg时存在问题。所以我尝试了一堆不同的东西,似乎无法让它工作。预先感谢您的帮助。保存和加载UIImages

我的继承人一次影像选择(我给了用户拍摄照片或选择一个图片从相机胶卷的选项)代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; 
    if (!image) image = [info objectForKey:UIImagePickerControllerOriginalImage]; 

    if (!image) 
     return; 

    NSData *imageData = UIImageJPEGRepresentation(image, 1.0); 
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

    NSString *whichPic = @"" 
    if (whichPicture == pictureA) 
     whichPic = @"kpictureA"; 
    else 
     whichPic = @"kpictureB"; 

    [defaults setObject:imageData forKey:whichPic]; 
    [defaults synchronize]; 

我想这一点,但不能得到它的工作:

// Create paths to output images 
    NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Before.png"]; 
    NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Before.jpg"]; 

    // Write a UIImage to JPEG with minimum compression (best quality) 
    // The value 'image' must be a UIImage object 
    // The value '1.0' represents image compression quality as value from 0.0 to 1.0 
    [UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES]; 

    // Write image to PNG 
    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES]; 

    // Let's check to see if files were successfully written... 

    // Create file manager 
    NSError *error; 
    NSFileManager *fileMgr = [NSFileManager defaultManager]; 

    // Point to Document directory 
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 

    // Write out the contents of home directory to console 
    NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); 
    */ 

我也试过,但无济于事:

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; 
    NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata]; 
    [library writeImageToSavedPhotosAlbum:[image CGImage] metadata:metadata completionBlock:nil]; 

然后加载图像时的视图负荷,我尝试这样做:

// Create paths to output images 
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Before.png"]; 
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Before.jpg"]; 


// Let's check to see if files were successfully written... 

// Create file manager 
NSError *error; 
NSFileManager *fileMgr = [NSFileManager defaultManager]; 

// Point to Document directory 
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 

// Write out the contents of home directory to console 
NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); 


if ([[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error] containsObject:@"pictureA.png"]) { 
    NSData *imageData = [fileMgr contentsAtPath:@"Documents/Before.png"]; 
    [pcitureAButton setImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal]; 
} 
else if ([fileMgr contentsAtPath:@"Documents/pictureA.png"]) { 
    NSData *imageData = [fileMgr contentsAtPath:@"Documents/pictureA.png"]; 

    [pictureButton setImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal]; 
} 

然后我试图这样:

if([defaults valueForKey:@"kPictureA"]) { 
    UIImage *image = [[UIImage alloc] initWithData:[defaults valueForKey:kPictureA]]; 
    [pictureAButton setImage:image forState:UIControlStateNormal]; 
} 

最后我尝试了使用与NSDataNSUserDefeaults

我宁愿使用NSUserDefaults,因为我对他们最舒服,但我肯定会打开解决方案。

回答

5

这是我用:

采取从图书馆

- (IBAction)openPhotoLibrary:(id)sender{ 

    UIImagePickerController *libraryPicker = [[UIImagePickerController alloc] init]; 
    libraryPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
    libraryPicker.allowsEditing = YES; 
    libraryPicker.delegate = self; 
    //Displays only picture option; 
    libraryPicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage]; 

    [self presentModalViewController: libraryPicker animated: YES]; 

    [libraryPicker release]; 
} 

响应用户敲击取消照片

- (IBAction)openCamera:(id)sender{ 

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == YES){ 

     UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init]; 
     cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera; 
     cameraUI.allowsEditing = YES; 
     cameraUI.delegate = self; 
     //Displays only picture option;   
     cameraUI.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage]; 

     [self presentModalViewController: cameraUI animated: YES]; 

     [cameraUI release]; 

    }else{ 
     [self openPhotoLibrary:nil]; 
    } 
} 

选择照片。

- (void)imagePickerControllerDidCancel: (UIImagePickerController *) picker { 

    [[picker parentViewController] dismissModalViewControllerAnimated: YES]; 
    [picker release]; 
} 

响应所述用户接受一个新捕获的图象

- (void) imagePickerController: (UIImagePickerController *) picker 
didFinishPickingMediaWithInfo: (NSDictionary *) description { 

    NSString *mediaType = [description objectForKey: UIImagePickerControllerMediaType]; 
    UIImage *originalImage, *editedImage, *imageToSave; 

    // Handle a still image capture 
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) { 

     editedImage = (UIImage *) [description objectForKey:UIImagePickerControllerEditedImage]; 
     originalImage = (UIImage *) [description objectForKey:UIImagePickerControllerOriginalImage]; 

     if (editedImage) { 
      imageToSave = editedImage; 
     } else { 
      imageToSave = originalImage; 
     } 

     // Save the new image (original or edited) to the Camera Roll 
     if(picker.sourceType == UIImagePickerControllerSourceTypeCamera) 
      UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil); 


     //Save your UIImage here 

     myImage = imageToSave; 

    } 

    [self dismissModalViewControllerAnimated:YES]; 
} 

EDIT

要检查文件类型可以使用以下方法考试系统第一NSData的字节:

+ (NSString *)contentTypeForImageData:(NSData *)data { 
    uint8_t c; 
    [data getBytes:&c length:1]; 

    switch (c) { 
    case 0xFF: 
     return @"image/jpeg"; 
    case 0x89: 
     return @"image/png"; 
    case 0x47: 
     return @"image/gif"; 
    case 0x49: 
    case 0x4D: 
     return @"image/tiff"; 
    } 
    return nil; 
} 
+0

如何检查它是否为.png或.jpeg,将其转换为NSData时将其保存起来很重要? – Andrew 2012-01-08 22:55:56

+0

@Andrew检查编辑,你会发现一个方法,只会做你所问。 – Cyprian 2012-01-08 23:07:40

+0

是否有无论如何,我使该方法的参数'UIImage',因为为了检查'NSData'来查看它是否为jpeg/png,我必须将其转换为NSData。并将其转换为NSData,我需要知道它是一个JPEG或PNG。哈哈 – Andrew 2012-01-10 17:29:33

3

一旦您在UI中具有图像ImageView的,你可以决定保存它以哪种方式你喜欢

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *imageName = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];  
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)]; 
[imageData writeToFile:imageName atomically:YES]; 

NSData的线从UIImageView.image将图像转换成PNG格式,因此被保存为.png文件扩展名的png格式

如果我想将它保存为JPEG ,只需将imageName更改为@“Image。JPG”和UIImagePNGRepresentation 改变UIImageJPEGRepresentation

现在相同的图像保存为JPEG格式。你决定的格式,然后使用匹配的文件扩展名和代表呼吁

塞浦路斯的答案给你读取图像的方法(从文件到NSData),并验证它是PNG还是JPEG等。