将图像保存到自定义文件夹titanium

时间:2016-04-28 10:37:11

标签: android ios iphone swift titanium

我开发了一款应用程序,用于从手机摄像头拍摄照片。但是现在我需要将图像存储到手机存储器中,然后存储到我创建的文件夹中。

我试过这个:

var filename = Titanium.Filesystem.resourcesDirectory + "/newImageFile.jpg";
var imageFile = Titanium.Filesystem.getFile(filename);
imageFile.write(capturedImg);

但它并没有在画廊中出现。如何将图像存储到手机存储器中?如何在手机存储器中创建服装文件夹以存储图像?

2 个答案:

答案 0 :(得分:0)

这将创建相册并保存到此相册中。

我想出了这个单例类来处理它:

import Photos

class CustomPhotoAlbum {

static let albumName = "Titanium"
static let sharedInstance = CustomPhotoAlbum()

var assetCollection: PHAssetCollection!

init() {

    func fetchAssetCollectionForAlbum() -> PHAssetCollection! {

        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
        let collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)

        if let firstObject: AnyObject = collection.firstObject {
            return collection.firstObject as! PHAssetCollection
        }

        return nil
    }

    if let assetCollection = fetchAssetCollectionForAlbum() {
        self.assetCollection = assetCollection
        return
    }

    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
        PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName)
    }) { success, _ in
        if success {
            self.assetCollection = fetchAssetCollectionForAlbum()
        }
    }
}

func saveImage(image: UIImage) {

    if assetCollection == nil {
        return   // If there was an error upstream, skip the save.
    }

    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
        let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
        let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
        let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection)
        albumChangeRequest.addAssets([assetPlaceholder])
    }, completionHandler: nil)
}

}

首次实例化该类时,如果自定义相册尚​​不存在,则会创建该相册。您可以保存这样的图像:

CustomPhotoAlbum.sharedInstance.saveImage(image)

注意:CustomPhotoAlbum类假定应用已拥有访问照片库的权限。处理权限有点超出了这个问题/答案的范围。 因此,请在使用之前确保PHPhotoLibrary.authorizationStatus()== .Authorize。并在必要时请求授权。

答案 1 :(得分:0)

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
            {
            NSData *imageData =  [info objectForKey:UIImagePickerControllerOriginalImage];   
    if(picker.sourceType==UIImagePickerControllerSourceTypeCamera)
      {
      //to save camera roll
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
           [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                                            } completionHandler:nil];
      }

            }

这将保存您拍摄的相机胶卷中的图像