2015-06-04 46 views
7

我正在開發一款應用程序,允許用戶使用PhotoKit編輯照片。我以前曾將編輯過的照片保存爲JPEG格式的磁盤。我想避免轉換爲JPEG,並已執行修改,以此來做到這一點。它適用於使用相機拍攝的照片,但如果您嘗試編輯屏幕截圖,PHPhotoLibrary.sharedPhotoLibrary().performChanges模塊將失敗並記錄The operation couldn’t be completed. (Cocoa error -1.)。我不知道爲什麼這會導致performChanges塊失敗,我在這裏做了什麼錯誤?無法編輯截圖,performChanges塊失敗

我創建了一個演示問題的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 
    } 
} 

回答

0

發生該問題是由於一個事實,即調整後的照片始終保存爲JPG文件,而屏幕截圖實際上是PNG文件。

我在調試您的示例項目時發現,在PhotoEditor中看到contentEditingOutput.renderedContentURL是JPG的URL,而如果您檢查CGImageSourceGetType(imageSource)的結果,則很明顯這是一個PNG(返回一個PNG UTI :public.png)。

所以我就去看了documentationrenderedContentURL其中規定,如果編輯照片資產,改變圖像是用JPEG格式 - 這,如果你的圖片是一個PNG顯然是行不通的。這導致我認爲蘋果不支持編輯PNG文件或不希望你。去圖..

+0

我已經記錄了一個蘋果的錯誤。這個錯誤也存在於iOS 9和10中。顯然不是他們要解決的高優先級。 – jjxtra