如何以编程方式将图像保存在自定义位置?

时间:2017-09-19 09:16:51

标签: ios xamarin xamarin.ios uiimage

我需要将图像保存在iOS中的自定义文件夹位置。我使用以下代码保存图像,同时保存在设备的默认位置。

        UIGraphics.BeginImageContext(nativechart.Frame.Size);
        nativechart.Layer.RenderInContext(UIGraphics.GetCurrentContext());

        UIImage image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        //Captured chart image will save into photo album

        image.SaveToPhotosAlbum(new UIImage.SaveStatus(delegate (UIImage img, NSError error) { }));

        ////save image

        NSData data = image.AsJPEG(1.0f);
        NSFileManager fileManager = NSFileManager.DefaultManager;
        string[] paths = NSSearchPath.GetDirectories(NSSearchPathDirectory.PicturesDirectory, NSSearchPathDomain.All, true);
        string documentsDirectory = paths[0];
        string fullPath = documentsDirectory + "/" + filename;
        fileManager.CreateFile(fullPath, data, new NSDictionary());

你能帮我把图像保存在自定义文件夹位置吗?

1 个答案:

答案 0 :(得分:2)

以下是在文档目录中保存图像的代码

   var photo = yourImageFile as UIImage;
   var documentsDirectory = Environment.GetFolderPath
                         (Environment.SpecialFolder.Personal);
    var directoryname = Path.Combine(documentsDirectory, "FolderName");
   Directory.CreateDirectory(directoryname);
   string jpgFilename = System.IO.Path.Combine (directoryname, "Photo.jpg"); // hardcoded filename, overwritten each time. You can make it dynamic as per your requirement.

   NSData imgData = photo.AsJPEG();
   NSError err = null;
   if (imgData.Save(jpgFilename, false, out err)) {
       Console.WriteLine("saved as " + jpgFilename);
   } else {
       Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
   }

来源Link