将UIImage保存为Xamarin.iOS中照片库目录中的jpg文件

时间:2017-08-17 09:36:24

标签: file xamarin xamarin.ios uiimage save

据我所知,这是将Approch保存在照片库中。但它可以使用自定义文件名保存。

var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
    var o = image as UIImage;
    Console.WriteLine("error:" + error);
})

但我想用照片库中的filename.jpg保存它。

我尝试了很多代码,但没有任何东西可以帮助我。

代码1:

var imageName = "/" + dicomId.ToString() + ".jpg";

var documentsDirectory = Environment.GetFolderPath
                    (Environment.SpecialFolder.Personal);

string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.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);
}

此代码部分转到if条件,但无法保存图像。

代码2:

如果使用此部分代码

var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];

它使您无权保存图像。

我在谷歌和SO上尝试了很多东西,但没有什么可以帮助我。

修改:

info.plist中

enter image description here

任何帮助都会得到赞赏。

1 个答案:

答案 0 :(得分:0)

如何使用UIImage.SaveToPhotosAlbum()

用法类似于:

image.SaveToPhotosAlbum((uiImage, nsError) =>
{
    if (nsError != null)
        // do something about the error..
    else
        // image should be saved
});

在尝试保存之前,请确保您已请求权限。

PHPhotoLibrary.RequestAuthorization(status =>
{
    switch (status)
    {
        case PHAuthorizationStatus.Restricted:
        case PHAuthorizationStatus.Denied:
            // nope you don't have permission
            break;
        case PHAuthorizationStatus.Authorized:
            // yep it is ok to save
            break;
    }
});

编辑:如果您想要更多控制权,则需要使用PHPhotosLibrary,这是一个糟糕的API ......

var library = PHPhotoLibrary.SharedPhotoLibrary;

var albumName = "MyPhotos";

var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
    PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);

var collection = assetsCollections.firstObject as PHAssetCollection;

library.PerformChanges(() => {
    var options = new PHAssetResourceCreationOptions();
    options.OriginalFilename = "filename.jpg";
    var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
    createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);

    // if you want to save to specific album... otherwise just remove these three lines
    var placeholder = createRequest.PlaceholderForCreatedAsset;
    var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
    albumChangeRequest.AddAssets(new PHObject[] { placeholder });
}, 
(ok, error) => {
    if (error != null)
    {
        // someone set up us the bomb
    }
});