從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"];就像我之前說過的那樣,我已經(jīng)嘗試了幾種方法來實現(xiàn)它,但無法掌握它。在我生命中我第一次想要對無生命的物體造成身體傷害,但我已經(jīng)設法克制自己。我希望能夠將用戶放置在應用程序文檔文件夾中的UIImageView中的圖像保存,然后能夠檢索它并將其放在另一個UIImageView中,以便在用戶將該視圖推送到堆棧時顯示。任何幫助是極大的贊賞!
3 回答

慕婉清6462132
TA貢獻1804條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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 關注
- 616 瀏覽
添加回答
舉報
0/150
提交
取消