gpt4 book ai didi

ios - 以更少的步骤从原始数据到 UIImagePNGRepresentation

转载 作者:行者123 更新时间:2023-11-29 11:51:41 39 4
gpt4 key购买 nike

使用此代码,我从共享扩展中提取一张图像,并将其写入我在应用程序组中创建的目录。

let content = self.extensionContext!.inputItems[0] as! NSExtensionItem

let contentType = kUTTypeImage as String

for attachment in content.attachments as! [NSItemProvider] {

if attachment.hasItemConformingToTypeIdentifier(contentType) {

attachment.loadItem(forTypeIdentifier: contentType, options: nil) { data, error in

// from here
if error == nil {

let url = data as! NSURL
let originalFileName = url.lastPathComponent

if let imageData = NSData(contentsOf: url as URL) {

let img = UIImage(data:imageData as Data)

if let data = UIImagePNGRepresentation(img!) {
// write, etc.
}

}
}

}

一切正常。

我想知道是否可以减少一些代码:特别是在 if error == nil 之后,我:

  • 将数据转换到NSURL;
  • 使用NSURL获取NSData
  • 使用NSData获取UIImage
  • 使用UIImage获取UIImagePNGRepresentation

除了避免创建 imageData 变量之外,是否有一种方法可以(安全地)以更少的步骤实现相同的目标?

最佳答案

首先你需要使用原生的 DataURL 而不是 NSData & NSURL 如果你想在 DocumentDirectory 中写入文件,那么您可以直接使用该 imageData,无需从中创建 UIImage 对象,然后使用 UIImagePNGRepresentation 将其转换为数据.

if let url = data as? URL, error == nil {

let originalFileName = url.lastPathComponent
if let imageData = try? Data(contentsOf: data) {
// write, etc.
var destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
destinationURL.appendPathComponent("fileName.png")
try? imageData.write(to: destinationURL)
}
}

关于ios - 以更少的步骤从原始数据到 UIImagePNGRepresentation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40840061/

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