簡體   English   中英

iOS Swift 4:從didFinishPickingMediaWithInfo獲取圖像格式(JPG,PNG,GIF)

[英]iOS Swift 4: Get Image Format (JPG,PNG,GIF) From didFinishPickingMediaWithInfo

我正在構建一個應用程序,允許您將圖像從庫上傳到服務器。 該服務器本質上用作映像存儲庫。 因此,絕對有必要將其存儲為原始圖像格式:JPG,PNG或GIF。 IE如果PNG圖像具有透明度(必須保留),則不能簡單地將其轉換為JPG。

我曾經使用UIImagePickerControllerReferenceURL獲得圖像格式:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let selectedImage = info[UIImagePickerControllerEditedImage] as! UIImage
        let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL

        if (assetPath.absoluteString?.hasSuffix("JPG"))! {
            print("JPG")
        }
        else if (assetPath.absoluteString?.hasSuffix("PNG"))! {
            print("PNG")
        }
        else if (assetPath.absoluteString?.hasSuffix("GIF"))! {
            print("GIF")
        }
        else {
            print("Unknown")
        }

        self.dismiss(animated: true, completion: nil)

        self.showImageFieldModal(selectedImage: selectedImage)
    }

但是UIImagePickerControllerReferenceURL在iOS11中已被棄用。 它建議使用UIImagePickerControllerPHAsset,但這不是URL。 我不確定作為PHAsset對象該怎么辦...

在iOS11中,您可以使用原始圖像url鍵UIImagePickerControllerImageURL並使用URL resourceValues方法獲取其typeIdentifierKey

if #available(iOS 11.0, *) {
    if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
        print(imageURL.typeIdentifier ?? "unknown UTI")  // this will print public.jpeg or another file UTI
    }
} else {
        // Fallback on earlier versions
}

您可以使用以下答案中typeIdentifier擴展名來找到fileURL類型標識符:

extension URL {
    var typeIdentifier: String? {
        return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM