如何将UIImage重新保存到同一路径

时间:2016-04-26 09:00:29

标签: ios objective-c uiimage nsurl save-image

我有一个使用设备相机捕获的UIImage,捕获图像后,我正在保存这样的UIImage,

-(void)onCapture:(UIImage *)image {
  NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

  NSFileManager *filemanager = [NSFileManager defaultManager];
  NSString *pathToImage = [NSTemporaryDirectory() stringByAppendingPathComponent:@"my_photo_001.jpg"];

  [filemanager createFileAtPath:pathToImage contents:imageData attributes:nil];

  NSURL *imageFileUrl = [NSURL fileURLWithPath:pathToImage];
  [self.delegate onDone:imageFileUrl];
}

将NSURL传递给委托后,委托然后将此NSURL传递给图像编辑视图控制器,我将UIImage以及NSURL传递给编辑视图控制器,一旦某人完成编辑,我想覆盖UIImage存储在NSURL与编辑的UIImage,所以我这样做,

NSData *imageData = UIImageJPEGRepresentation(self.editImage.image, 1.0);
NSString *pathToImage = [pathOfCapturedImage absoluteString];
[imageData writeToFile:pathToImage atomically:YES];

NSURL *imageFileUrl = [NSURL URLWithString:pathToImage];

其中pathOfCapturedImage是我传递给编辑视图控制器的变量。

然而,当我在保存后打开图像时会打开未经编辑的图像,我哪里出错?

2 个答案:

答案 0 :(得分:0)

您可以先尝试删除旧文件,然后编写新文件;

distribution

答案 1 :(得分:0)

首先删除旧的存在图像,然后在同一路径上写入。

NSString* imagePath = @"image path"; // get path of old image.

NSData *imgData = UIImageJPEGRepresentation(self.editImage.image, 1.0); // get data of edited image. please make sure if edited image is not nil.


if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) // check existence of old image, If yes then delete it.
{
    [[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
}

if (imgData)
    [imgData writeToFile:imagePath atomically:YES];