草庐IT

ios - AVMediaTypeVideo 捕获静止图像方向

coder 2023-09-07 原文

我已经看到了这个问题的其他几乎答案,但似乎无法让它发挥作用。我正在从 AVMediaTypeVideo 捕获图像,它的方向始终是 UIImageOrientation 3(我不知道这在现实中意味着什么)。

我尝试使用状态栏方向来纠正它,但似乎没有任何效果。我不需要将这些图像保存到相机胶卷,它现在就在那里进行验证。我不确定这是否也对方向有任何影响。

import UIKit
import AVFoundation

class ViewController: UIViewController {

let captureSession = AVCaptureSession()
let stillImageOutput = AVCaptureStillImageOutput()

var avCaptureVideoPreview : AVCaptureVideoPreviewLayer?

var error: NSError?

override func viewDidLoad() {
    super.viewDidLoad()

    let devices = AVCaptureDevice.devices().filter{ $0.hasMediaType(AVMediaTypeVideo) }

    if let captureDevice = devices.first as? AVCaptureDevice  {

        captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &error))

        captureSession.sessionPreset = AVCaptureSessionPresetMedium

        captureSession.startRunning()

        stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]

        if captureSession.canAddOutput(stillImageOutput) {

            captureSession.addOutput(stillImageOutput)
        }

        avCaptureVideoPreview = AVCaptureVideoPreviewLayer(session: captureSession)

        if let previewLayer = avCaptureVideoPreview {

            previewLayer.bounds = CGRectMake(0.0, 0.0, view.bounds.size.width, view.bounds.size.height)

            previewLayer.position = CGPointMake(view.bounds.midX, view.bounds.midY)

            previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

            let cameraPreview = UIView(frame: CGRectMake(0.0, 0.0, view.bounds.size.width, view.bounds.size.height))

            cameraPreview.layer.addSublayer(previewLayer)

            cameraPreview.addGestureRecognizer(UITapGestureRecognizer(target: self, action:"saveToCamera:"))

            view.addSubview(cameraPreview)
        }
    }

    // Add a selfie button if device is capable

    for device in devices {

        if device.position == AVCaptureDevicePosition.Front {

            // Add selfie button
            println("selfie capable")
        }

    }

}

override func viewWillLayoutSubviews() {

    if avCaptureVideoPreview != nil {

        // Orientation

        if (avCaptureVideoPreview!.connection.supportsVideoOrientation == true) {

            avCaptureVideoPreview!.connection.videoOrientation = interfaceOrientationToVideoOrientation(UIApplication.sharedApplication().statusBarOrientation)
        }

        // Frame 

        avCaptureVideoPreview!.bounds = CGRectMake(0.0, 0.0, view.bounds.size.width, view.bounds.size.height)

        avCaptureVideoPreview!.position = CGPointMake(view.bounds.midX, view.bounds.midY)

        avCaptureVideoPreview!.videoGravity = AVLayerVideoGravityResizeAspectFill

    }
}

func interfaceOrientationToVideoOrientation(orientation: UIInterfaceOrientation) -> AVCaptureVideoOrientation {

    switch orientation {

    case UIInterfaceOrientation.Portrait:
        return AVCaptureVideoOrientation.Portrait
    case UIInterfaceOrientation.PortraitUpsideDown:
        return AVCaptureVideoOrientation.PortraitUpsideDown
    case UIInterfaceOrientation.LandscapeLeft:
        return AVCaptureVideoOrientation.LandscapeLeft
    case UIInterfaceOrientation.LandscapeRight:
        return AVCaptureVideoOrientation.LandscapeRight
    default:
        return AVCaptureVideoOrientation.Portrait

    }

}

func saveToCamera(sender: UITapGestureRecognizer) {

    if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) {

        stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {

            (imageDataSampleBuffer, error) -> Void in

            var image = UIImage(data: AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer))

            // this is not working
            var orientation : UIImageOrientation?

            switch UIApplication.sharedApplication().statusBarOrientation.rawValue {

            case 1:
                orientation = UIImageOrientation.Up
            case 3:
                orientation = UIImageOrientation.Left
            case 4:
                orientation = UIImageOrientation.Right
            default:
                orientation = UIImageOrientation.Up

            }

            let newImage = UIImage(CGImage: image?.CGImage, scale: 1.0, orientation: orientation!)

            UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)

        }
    }
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

最佳答案

编辑,这不适用于使用前置摄像头拍摄的照片,它们在 native 照片应用程序中显示正常,但在 Mac 上的“照片”中共享或从 parse.com 加载回时则不然。

感谢@XJones 在这里的回答Why does AVCaptureVideoOrientation landscape modes result in upside down still images?

import UIKit
import AVFoundation

class ViewController: UIViewController {

let captureSession = AVCaptureSession()
let stillImageOutput = AVCaptureStillImageOutput()

var avCaptureVideoPreview : AVCaptureVideoPreviewLayer?

var error: NSError?

override func viewDidLoad() {
    super.viewDidLoad()

    let devices = AVCaptureDevice.devices().filter{ $0.hasMediaType(AVMediaTypeVideo) }

    if let captureDevice = devices.first as? AVCaptureDevice  {

        captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &error))

        captureSession.sessionPreset = AVCaptureSessionPresetMedium

        captureSession.startRunning()

        stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]

        if captureSession.canAddOutput(stillImageOutput) {

            captureSession.addOutput(stillImageOutput)
        }

        avCaptureVideoPreview = AVCaptureVideoPreviewLayer(session: captureSession)

        if let previewLayer = avCaptureVideoPreview {

            previewLayer.bounds = CGRectMake(0.0, 0.0, view.bounds.size.width, view.bounds.size.height)

            previewLayer.position = CGPointMake(view.bounds.midX, view.bounds.midY)

            previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

            let cameraPreview = UIView(frame: CGRectMake(0.0, 0.0, view.bounds.size.width, view.bounds.size.height))

            cameraPreview.layer.addSublayer(previewLayer)

            cameraPreview.addGestureRecognizer(UITapGestureRecognizer(target: self, action:"saveToCamera:"))

            view.addSubview(cameraPreview)
        }
    }

    // Add a selfie button if device is capable

    for device in devices {

        if device.position == AVCaptureDevicePosition.Front {

            // Add selfie button
            println("selfie capable")
        }

    }

}

override func viewWillLayoutSubviews() {

    if avCaptureVideoPreview != nil {

        // Orientation

        if (avCaptureVideoPreview!.connection.supportsVideoOrientation == true) {

            var newOrientation : AVCaptureVideoOrientation?

            switch UIDevice.currentDevice().orientation {
            case UIDeviceOrientation.Portrait:
                newOrientation = AVCaptureVideoOrientation.Portrait
            case UIDeviceOrientation.PortraitUpsideDown:
                newOrientation = AVCaptureVideoOrientation.PortraitUpsideDown
            case UIDeviceOrientation.LandscapeLeft:
                newOrientation = AVCaptureVideoOrientation.LandscapeRight;
            case UIDeviceOrientation.LandscapeRight:
                newOrientation = AVCaptureVideoOrientation.LandscapeLeft
            default:
                newOrientation = AVCaptureVideoOrientation.Portrait
            }

            avCaptureVideoPreview!.connection.videoOrientation = newOrientation!

        }

        // Frame 

        avCaptureVideoPreview!.bounds = CGRectMake(0.0, 0.0, view.bounds.size.width, view.bounds.size.height)

        avCaptureVideoPreview!.position = CGPointMake(view.bounds.midX, view.bounds.midY)

        avCaptureVideoPreview!.videoGravity = AVLayerVideoGravityResizeAspectFill

    }
}

func saveToCamera(sender: UITapGestureRecognizer) {

    if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) {

        stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {

            (imageDataSampleBuffer, error) -> Void in

            var image = UIImage(data: AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer))

            var imageOrientation : UIImageOrientation?

            switch UIDevice.currentDevice().orientation {

            case UIDeviceOrientation.PortraitUpsideDown:
                imageOrientation = UIImageOrientation.Left
            case UIDeviceOrientation.LandscapeRight:
                imageOrientation = UIImageOrientation.Down
            case UIDeviceOrientation.LandscapeLeft:
                imageOrientation = UIImageOrientation.Up
            case UIDeviceOrientation.Portrait:
                imageOrientation = UIImageOrientation.Right
            default:
                imageOrientation = UIImageOrientation.Right

            }

            var newImage = UIImage(CGImage: image!.CGImage, scale: 1.0, orientation: imageOrientation!)

            UIImageWriteToSavedPhotosAlbum(newImage!, nil, nil, nil)

        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

关于ios - AVMediaTypeVideo 捕获静止图像方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436994/

有关ios - AVMediaTypeVideo 捕获静止图像方向的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  4. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  5. ruby-on-rails - 在 Ruby (on Rails) 中使用 imgur API 获取图像 - 2

    我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path

  6. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

  7. ruby - 如何让Ruby捕获线程中的语法错误 - 2

    我正在尝试使用ruby​​编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?

  8. ruby-on-rails - 无法在 Rails 助手中捕获 block 的输出 - 2

    我在使用自定义RailsFormBuilder时遇到了问题,从昨天晚上开始我就发疯了。基本上我想对我的构建器方法之一有一个可选block,以便我可以在我的主要content_tag中显示其他内容。:defform_field(method,&block)content_tag(:div,class:'field')doconcatlabel(method,"Label#{method}")concattext_field(method)capture(&block)ifblock_given?endend当我在我的一个Slim模板中调用该方法时,如下所示:=f.form_field:e

  9. ruby - 是否有将图像文件转换为 ASCII 艺术的命令行程序或库? - 2

    有这样的事吗?我想在Ruby程序中使用它。 最佳答案 试试这个http://csl.sublevel3.org/jp2a/此外,Imagemagick可能还有一些东西 关于ruby-是否有将图像文件转换为ASCII艺术的命令行程序或库?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/6510445/

  10. ruby-on-rails - 使用 Dragonfly 从 URL 分配图像 - 2

    我正在使用Dragonfly在Rails3.1应用程序上处理图像。我正在努力通过url将图像分配给模型。我有一个很好的表格:{:multipart=>true}do|f|%>RemovePicture?Dragonfly的文档指出:Dragonfly提供了一个直接从url分配的访问器:@album.cover_image_url='http://some.url/file.jpg'但是当我在控制台中尝试时:=>#ruby-1.9.2-p290>picture.image_url="http://i.imgur.com/QQiMz.jpg"=>"http://i.imgur.com/QQ

随机推荐