gpt4 book ai didi

Swift 将图像(屏幕截图)保存到 nsuserdefaults

转载 作者:行者123 更新时间:2023-11-28 07:01:27 24 4
gpt4 key购买 nike

我有一个程序,用户在其中“创建”一个图像,然后该程序截取屏幕截图。然后我想将此屏幕截图保存到数据库中,最好是 nsuserdefaults,因为稍后我将在 TableView 中访问它。非常欢迎关于如何解决这个问题的任何其他建议:)

代码是这样的

let screenshot = getScreenshot() // saves the screenshot
var imagePaths = [String]()
// get the array of previous screenshots
if let _ = NSUserDefaults.standardUserDefaults().objectForKey(theKey)
{
imagePaths = NSUserDefaults.standardDefaults().objectForKey(theKey) as! [String]
}
// then I want to get a path to the image something like
let imagePath = screenshot.getPath() // although this is not a valid method, this is basically what I want
// add the imagePath
imagePaths.append(imagePath)
// finally I save the image
NSUserDefaults.standardUserDefaults().setObject(imagePaths, forKey: theKey)

最佳答案

您可以在 Documents 中创建目录,并将屏幕截图作为普通文件保存在那里。文件名可以根据日期和时间生成,以确保唯一性。

func saveImage(imageData: NSData)
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh.mm.ss"
let filename = "\(dateFormatter.stringFromDate(NSDate())).png"

let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")
let filePath = imagesDirectory.stringByAppendingPathComponent(filename)

if !NSFileManager.defaultManager().fileExistsAtPath(imagesDirectory)
{
var error: NSError?

NSFileManager.defaultManager().createDirectoryAtPath(imagesDirectory, withIntermediateDirectories: false, attributes: nil, error: &error)

if error != nil
{
println("\(error!.localizedDescription)")
return
}
}

imageData.writeToFile(filePath, atomically: true)
}

func getImagesPaths() -> [String]?
{
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")

if let filenames = NSFileManager.defaultManager().contentsOfDirectoryAtPath(imagesDirectory, error: nil)
{
let imagePaths = filenames.map{"\(imagesDirectory)/\($0)"}.filter(){$0.pathExtension == "png"}
return imagePaths.count > 0 ? imagePaths : nil
}
return nil
}

要保存图像,只需使用saveImage(data)。要获取图像路径,请使用 getImagesPaths()

如果需要UIImage数组,可以通过以下方式获取:

var images : [UIImage] = [ ]
if let imagePaths = getImagesPaths()
{
for path in imagePaths
{
if let image = UIImage(contentsOfFile: path)
{
images.append(image)
}
}
}

关于Swift 将图像(屏幕截图)保存到 nsuserdefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com