我正在为iOS编写一款Swift应用程序。我想知道如何从用户的相机胶卷(或者现在他们叫它什么)中获取图像,并在应用程序内部将其保存到本地,以便稍后可以引用它。怎样才能做到这一点呢?例如,假设我想获取该图像并将其设置为Storyboard中UIImageView的图像。
我正在为iOS编写一款Swift应用程序。我想知道如何从用户的相机胶卷(或者现在他们叫它什么)中获取图像,并在应用程序内部将其保存到本地,以便稍后可以引用它。怎样才能做到这一点呢?例如,假设我想获取该图像并将其设置为Storyboard中UIImageView的图像。
UIImagePickerController
和NSUserDefaults
结合的作用。UIImagePickerController
捕获图像,然后将其存储在照片库中,或使用NSUserDefaults
将其存储在设备上。NSUserDefaults
存储图像,请参见此问题。let imageData = NSData(data:UIImagePNGRepresentation(pickedimage))
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as! String
let fullPath = docs.stringByAppendingPathComponent("yourNameImg.png")
let result = imageData.writeToFile(fullPath, atomically: true)
print(fullPath)
获取图像:
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
if paths.count > 0
{
if let dirPath = paths[0] as? String
{
let readPath = dirPath.stringByAppendingPathComponent("yourNameImg.png")
let image = UIImage(contentsOfFile: readPath)
UploadImagePreview.image = image
}
}
}
var fetchOptions: PHFetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
var fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)
if (fetchResult.firstObject != nil) {
var lastAsset: PHAsset = fetchResult.lastObject as! PHAsset
PHImageManager.defaultManager().requestImageForAsset(lastAsset, targetSize: self.UploadImagePreview.bounds.size, contentMode: PHImageContentMode.AspectFill, options: PHImageRequestOptions(), resultHandler: { (result, info) -> Void in
self.UploadImagePreview.image = result
})
}
UIImagePickerController
选择图像,然后使用AssetsLibrary
保存到相册。一旦您获取了UIImage对象,您可以使用以下代码将图像保存在doc目录中
let imageData = NSData(data:UIImagePNGRepresentation(wineImage.image))
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as! String
let fullPath = docs.stringByAppendingPathComponent("yourNameImg.png")
let result = imageData.writeToFile(fullPath, atomically: true)
UIImagePickerController
,一旦你选择了图片,就可以使用这种文件管理器的方法。我不建议使用NSUserDefaults
来存储图片,因为这违反了Apple的指南。let imageData = UIImagePNGRepresentation(selectedImage)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let imagePath = paths.stringByAppendingPathComponent("cached.png")
if !imageData.writeToFile(imagePath, atomically: false)
{
println("not saved")
} else {
println("saved")
NSUserDefaults.standardUserDefaults().setObject(imagePath, forKey: "imagePath")
}