如何处理图像方向

时间:2016-07-02 09:34:46

标签: swift uiimagepickercontroller

我对相机拍摄图像有疑问。当我使用UIImagePickerController从相机捕获图像时和捕获后,我将图像保存在我的文档目录中并将其显示在我的自定义collectionView上。但问题是当我捕获图像并将其保存到文档目录时,当我在我的collectionView中加载图像时,它会向用户显示错误的方向,我该如何处理图像方向?我试图将图像保存为JPEG,但它只支持一种方向。我想将图像保存为png,因为它支持所有方向。

我的代码:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    // handle image orientation 

    //end

    // code for save image in document directory  from camera roll
    let fileManager = NSFileManager.defaultManager()
    do {
        let document = try fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
        let getFolders = try fileManager.contentsOfDirectoryAtURL(document, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)
        var maxImageNumber:Int = 0 // for get the max number image in document directory
        for folder in getFolders {
            if folder.lastPathComponent! == albumName {
                let getImagesCheck = try fileManager.contentsOfDirectoryAtURL(folder, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)
                let getImages = try fileManager.contentsOfDirectoryAtURL(folder, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)

                if getImages.count <= 0 {
                    let imageUrl = folder.URLByAppendingPathComponent("Image \(getImagesCheck.count + 1).png")
                    if let convertImage = UIImagePNGRepresentation(image) {
                        convertImage.writeToURL(imageUrl, atomically: true)
                    }
                }else {
                    // continue save images
                    let getImages_else = try fileManager.contentsOfDirectoryAtURL(folder, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)

                    for img in getImages_else {
                        let getImageName = img.lastPathComponent!
                        let arrayOne = getImageName.componentsSeparatedByString(".")
                        let arrayTwo = arrayOne[0].componentsSeparatedByString(" ")
                        let getImageNumber = Int(arrayTwo[1])
                        if getImageNumber! > maxImageNumber {
                            maxImageNumber = getImageNumber!
                        }
                    }

                    let imageUrl = folder.URLByAppendingPathComponent("Image \(maxImageNumber + 1).png")
                    if let convertImage = UIImagePNGRepresentation(image) {
                        convertImage.writeToURL(imageUrl, atomically: true)
                    }

                }
            }
        }

    }catch {
        print(error)
    }

    self.dismissViewControllerAnimated(true, completion: nil)
}

0 个答案:

没有答案