【问题标题】:Save Imagedata in the imageview将图像数据保存在图像视图中
【发布时间】:2014-10-23 07:51:54
【问题描述】:

在应用程序中,我创建了一个图像视图,其中包含从手机库中选择或由相机拍摄的图像。但是当我回到前一个场景时,选择的图像消失了。我希望它保存在图像视图中并有一个清除按钮来删除它。相机功能有效,但图像不会停留在图像视图中。

相机功能: .h 文件

@interface FMEImageView : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
IBOutlet UIImageView *ImageView;
UIImagePickerController *picker;

UIImage *image;

}

- (IBAction)Takephoto:(id)sender;
- (IBAction)Chosenphoto:(id)sender;
@end

.m 文件

- (IBAction)Takephoto:(id)sender{
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];


}

- (IBAction)Chosenphoto:(id)sender{
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker animated:YES completion:NULL];


 }

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

image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[ImageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}

- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}

【问题讨论】:

    标签: ios objective-c uiimageview uiimagepickercontroller


    【解决方案1】:

    我认为,您必须将图像保存到应用程序的文档目录中。

    获取图像数据。

    NSData *imgData = UIImagePNGRepresentation(image);
    

    将其写入文档目录。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *documentsPath = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"];//Choose name for the image. 
    
    [imgData writeToFile:filePath atomically:YES]; //Write the file
    

    获取数据并将其显示在 imageView 上。

    再次,获取文件路径。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *documentsPath = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"];//Name you have given    
    
    NSData *imgData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage imageWithData:imgData];
    
    imageView.image = image;
    

    最好做个函数来获取文档目录的路径。

    希望对你有帮助。

    【讨论】:

    • 在我从相机库中选择图像或拍摄照片之前,即使图像视图是空的,这也能正常工作吗?
    • 是的!这就是重点,对吧?除非并且直到您没有图像,否则它不会显示任何内容。
    【解决方案2】:

    您可能每次都在使用新实例。初始化后使用相同的实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 2011-02-14
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多