从IIV上的UIView将图像保存到应用程序文档文件夹我有一个UIImageView,允许用户放置和保存图像,直到它可以保存。问题是,我无法弄清楚如何实际保存和检索我放在视图中的图像。我检索并将图像放在UIImageView中,如下所示://Get Image - (void) getPicture:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:picker animated:YES];
[picker release];}- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo {
myPic.image = image;
[picker dismissModalViewControllerAnimated:YES];}它在我的UIImageView中显示所选图像就好了,但我不知道如何保存它。我正在Core Data中保存视图的所有其他部分(主要是UITextfield)。我搜索并搜索过,并尝试过人们建议的许多代码,但要么我没有正确输入代码,要么这些建议与我设置代码的方式无关。这可能是前者。我想使用相同的操作(保存按钮)将图像保存在UIImageView中我用来保存UITextFields中的文本。这是我如何保存我的UITextField信息:// Handle Save Button- (void)save {
// Get Info From UI
[self.referringObject setValue:self.myInfo.text forKey:@"myInfo"];就像我之前说过的那样,我已经尝试了几种方法来实现它,但无法掌握它。在我生命中我第一次想要对无生命的物体造成身体伤害,但我已经设法克制自己。我希望能够将用户放置在应用程序文档文件夹中的UIImageView中的图像保存,然后能够检索它并将其放在另一个UIImageView中,以便在用户将该视图推送到堆栈时显示。任何帮助是极大的赞赏!
3 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
Swift 3.0版
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSStringlet img = UIImage(named: "1.jpg")!// Or use whatever way to get the UIImage objectlet imgPath = URL(fileURLWithPath: documentDirectoryPath.appendingPathComponent("1.jpg"))// Change extension if you want to save as PNGdo{ try UIImageJPEGRepresentation(img, 1.0)?.write(to: imgPath, options: .atomic)//Use UIImagePNGRepresentation if you want to save as PNG}catch let error{ print(error.localizedDescription)}
富国沪深
TA贡献1790条经验 获得超9个赞
这是Fangming Ning 对Swift 4.2 的回答,更新了推荐的更多Swifty方法,用于检索文档目录路径和更好的文档。对于方明宁来说也是一种新方法。
guard let documentDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return}//Using force unwrapping here because we're sure "1.jpg" exists. Remember, this is just an example.let img = UIImage(named: "1.jpg")!// Change extension if you want to save as PNG.let imgPath = documentDirectoryPath.appendingPathComponent("1.jpg")do { //Use .pngData() if you want to save as PNG. //.atomic is just an example here, check out other writing options as well. (see the link under this example) //(atomic writes data to a temporary file first and sending that file to its final destination) try img.jpegData(compressionQuality: 1)?.write(to: imgPath, options: .atomic)} catch { print(error.localizedDescription)}
- 3 回答
- 0 关注
- 574 浏览
添加回答
举报
0/150
提交
取消