我正在开发一款允许用户使用 PhotoKit 编辑照片的应用程序。我之前将编辑后的照片以 JPEG 格式保存到磁盘。我想避免转换为 JPEG 并为此进行了修改。它非常适合用相机拍摄的照片,但如果您尝试编辑屏幕截图,PHPhotoLibrary.sharedPhotoLibrary().performChanges
block 将失败并记录 操作无法完成。 ( cocoa 错误 -1。)
。我不确定为什么这会导致 performChanges block 失败,我在这里做错了什么?
我创建了一个 sample app available to download这说明了问题,我在下面包含了相关代码。该应用程序会尝试编辑您照片库中的最新照片。如果成功,它会提示编辑照片的权限,否则什么也不会发生,您将看到控制台日志。要重现该问题,请截取屏幕截图,然后运行该应用。
适用于屏幕截图的当前代码:
let jpegData: NSData = outputPhoto.jpegRepresentationWithCompressionQuality(0.9)
let contentEditingOutput = PHContentEditingOutput(contentEditingInput: self.input)
var error: NSError?
let success = jpegData.writeToURL(contentEditingOutput.renderedContentURL, options: NSDataWritingOptions.AtomicWrite, error: &error)
if success {
return contentEditingOutput
} else {
return nil
}
导致截图失败的替换代码:
let url = self.input.fullSizeImageURL
let orientation = self.input.fullSizeImageOrientation
var inputImage = CIImage(contentsOfURL: url)
inputImage = inputImage.imageByApplyingOrientation(orientation)
let outputPhoto = createOutputImageFromInputImage(inputImage)!
let originalImageData = NSData(contentsOfURL: self.input.fullSizeImageURL)!
let imageSource = CGImageSourceCreateWithData(originalImageData, nil)
let dataRef = CFDataCreateMutable(nil, 0)
let destination = CGImageDestinationCreateWithData(dataRef, CGImageSourceGetType(imageSource), 1, nil) //getType automatically selects JPG, PNG, etc based on original format
struct ContextStruct {
static var ciContext: CIContext? = nil
}
if ContextStruct.ciContext == nil {
let eaglContext = EAGLContext(API: .OpenGLES2)
ContextStruct.ciContext = CIContext(EAGLContext: eaglContext)
}
let cgImage = ContextStruct.ciContext!.createCGImage(outputPhoto, fromRect: outputPhoto.extent())
CGImageDestinationAddImage(destination, cgImage, nil)
if CGImageDestinationFinalize(destination) {
let contentEditingOutput = PHContentEditingOutput(contentEditingInput: self.input)
var error: NSError?
let imageData: NSData = dataRef
let success = imageData.writeToURL(contentEditingOutput.renderedContentURL, options: .AtomicWrite, error: &error)
if success {
//it does succeed
return contentEditingOutput
} else {
return nil
}
}
最佳答案
出现此问题是因为调整后的照片总是保存为 JPG 文件,而屏幕截图实际上是 PNG 文件。
我在调试您的示例项目时突然想到,在 PhotoEditor 中,contentEditingOutput.renderedContentURL
是 JPG 的 URL,而如果您检查 CGImageSourceGetType( imageSource)
很明显它是一个 PNG(返回一个 PNG UTI:public.png)。
所以我去阅读了 documentation对于 renderedContentURL
,它声明如果编辑照片 Assets ,更改后的图像将以 JPEG 格式写入 - 如果您的图像是 PNG,这显然不起作用。这使我认为 Apple 不支持编辑 PNG 文件或不希望您这样做。去图..
关于ios - 无法编辑屏幕截图,performChanges block 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30636579/