保存和加载UIImages

时间:2011-12-30 17:21:12

标签: iphone ios uiimageview uiimage uiimagepickercontroller

所以在我的应用中,我希望用户能够选择/拍摄照片,然后在UIImageView中显示该图像。问题是,通过我的研究,我发现了许多保存/加载图像的方法,但显然知道图像是.png还是.jpg是个问题。所以我尝试了很多不同的东西,似乎无法让它发挥作用。提前感谢您的帮助。

一旦选择了图像,我就会看到我的代码(我给用户选择拍照或从相机胶卷中选择一张照片):

- (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因为我对它们感到最舒服,但我当然愿意接受有效的解决方案。

2 个答案:

答案 0 :(得分:5)

这就是我使用的:

拍张照片

- (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];
    }
}

从库中选择照片

- (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];
}

响应用户点击取消。

- (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];
}

修改

要检查文件类型,可以使用以下方法检查第一个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;
}

答案 1 :(得分:3)

在UIImageView中拥有Image后,您可以决定以您喜欢的格式保存它

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等。