ориентация изображения изменяется в ipad после захвата изображения в swift - PullRequest
0 голосов
/ 02 апреля 2019

Я хочу добавить изображение маркера на захваченном изображении с камеры, затем быстро сохранить в библиотеке фотографий, но изображение сохранено с неправильной ориентацией в библиотеке фотографий, поэтому, пожалуйста, предложите, как я исправлю эту проблему.Я хочу сохранить изображение в режиме Pot-Rate для iPhone и в режиме Lanscape для iPad.поэтому, пожалуйста, предложите, где я не прав.мой код там: {

    if let videoConnection = stillImageOutput.connection(with: AVMediaType.video) {

        stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (CMSampleBuffer, Error) in
            if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(CMSampleBuffer!) {

                if let cameraImage = UIImage(data: imageData) {



                    if let  img2 = self.imgWaterMark.image {



                       // let rect = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)

                        let rect = CGRect(x: 0, y: 0, width: (self.previewLayer?.frame.size.width)! , height: (self.previewLayer?.frame.size.height)!)

                        UIGraphicsBeginImageContextWithOptions((self.previewLayer?.frame.size)!, true, 180)
                        let context = UIGraphicsGetCurrentContext()

                        context?.setFillColor(UIColor.white.cgColor)
                        context?.fill(rect)

                        cameraImage.draw(in: rect, blendMode: .normal, alpha: 1)
                        img2.draw(in:self.imgWaterMark.frame , blendMode: .normal, alpha: 1)
                        let result = UIGraphicsGetImageFromCurrentImageContext()
                        UIGraphicsEndImageContext()

                       // let img = result

                        //let finalimage = self.rotateCameraImageToProperOrientation(imageSource: cameraImage)
                        UIImageWriteToSavedPhotosAlbum(result ?? cameraImage, nil, nil, nil)
                       // self.textToImage(drawText:self.lblTitle!.text! as NSString, inImage: result ?? cameraImage, atPoint: CGPoint(x: 0, y: 110))

                        AppSharedData.sharedInstance.showAlert(title: "", message: "Image saved", viewController: self, actions: ["OK"], callBack: { (action) in

                        })
                    }
                }
            }
        })
    }
}

1 Ответ

0 голосов
/ 02 апреля 2019

Я использовал приведенный ниже код для получения ориентации изображения и преобразования в требуемую ориентацию.Пожалуйста, посмотрите, если вы можете использовать это.

img_Photo.image = self.imageOrientation((img_Photo?.image)!)


//*******************************
func imageOrientation(_ src:UIImage)->UIImage {
    print(src.imageOrientation.rawValue)
    print(src.imageOrientation.hashValue)
    if src.imageOrientation == UIImageOrientation.up {
        return src
    }/*else if src.imageOrientation == UIImageOrientation.down {
        return src
    }else if src.imageOrientation == UIImageOrientation.left {
        return src
    }else if src.imageOrientation == UIImageOrientation.right {
        return src
    }*/

    var transform: CGAffineTransform = CGAffineTransform.identity
    switch src.imageOrientation {
    case UIImageOrientation.up, UIImageOrientation.upMirrored:
        transform = transform.translatedBy(x: src.size.width, y: src.size.height)
        transform = transform.rotated(by: CGFloat(M_PI))
        break
    case UIImageOrientation.down, UIImageOrientation.downMirrored:
        transform = transform.translatedBy(x: src.size.width, y: src.size.height)
        transform = transform.rotated(by: CGFloat(M_PI))
        break
    case UIImageOrientation.left, UIImageOrientation.leftMirrored:
        transform = transform.translatedBy(x: src.size.width, y: 0)
        transform = transform.rotated(by: CGFloat(M_PI_2))
        break
    case UIImageOrientation.right, UIImageOrientation.rightMirrored:
        transform = transform.translatedBy(x: 0, y: src.size.height)
        transform = transform.rotated(by: CGFloat(-M_PI_2))
        break

    }

    switch src.imageOrientation {
    case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored:
        transform.translatedBy(x: src.size.width, y: 0)
        transform.scaledBy(x: -1, y: 1)
        break
    case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored:
        transform.translatedBy(x: src.size.height, y: 0)
        transform.scaledBy(x: -1, y: 1)
    case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right:
        break
    }

    let ctx:CGContext = CGContext(data: nil, width: Int(src.size.width), height: Int(src.size.height), bitsPerComponent: (src.cgImage)!.bitsPerComponent, bytesPerRow: 0, space: (src.cgImage)!.colorSpace!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!

    ctx.concatenate(transform)

    switch src.imageOrientation {
    case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored:
        ctx.draw(src.cgImage!, in: CGRect(x: 0, y: 0, width: src.size.height, height: src.size.width))
        break
    default:
        ctx.draw(src.cgImage!, in: CGRect(x: 0, y: 0, width: src.size.width, height: src.size.height))
        break
    }

    let cgimg:CGImage = ctx.makeImage()!
    let img:UIImage = UIImage(cgImage: cgimg)

    return img
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...