【问题标题】:Saving and Loading UIImages保存和加载 UIImages
【发布时间】:2012-01-30 17:05:23
【问题描述】:

所以在我的应用程序中,我希望用户能够选择/拍照,然后在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,因为我最熟悉它们,但我当然愿意接受可行的解决方案。

【问题讨论】:

    标签: iphone ios uiimageview uiimage uiimagepickercontroller


    【解决方案1】:

    这是我用的:

    拍照

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

    【讨论】:

    • 如何检查它是 .png 还是 .jpeg,这在将其转换为 NSData 以保存时很重要?
    • @Andrew 查看编辑,您会发现一种方法可以满足您的要求。
    • 无论如何我将该方法的参数设为UIImage,因为为了检查NSData 是否为jpeg/png,我必须将其转换为NSData。要将其转换为 NSData,我需要知道它是 jpeg 还是 png。哈哈
    【解决方案2】:

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

    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。您决定格式,然后使用匹配的文件扩展名和表示调用

    Cyprian 答案为您提供了一种读取图像(从文件到 NSData)并验证它是 PNG 或 JPEG 等的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-08
      • 2013-01-13
      • 1970-01-01
      • 2019-11-08
      • 2018-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多