我有一个允许用户拍照的 View Controller 。我将 avcapture 边界设置为屏幕上 View 的边界。
在这个 View 之上我有一个 Collection View 。因此用户可以捕获多张照片,然后将它们添加到上面的 Collection View 中。
我在上面的预览中无法正确显示方向。
代码如下:
@IBOutlet weak var imagePreviews: UICollectionView!
@IBOutlet weak var imgPreview: UIView!
var session: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var images: [UIImage] = [UIImage]()
var isLandscapeLeft : Bool = false
var isLandscapeRight : Bool = false
var isPortrait : Bool = false
var isPortraitUpsideDown: Bool = false
@IBAction func capture(_ sender: UIButton)
{
if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
{
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) in
if sampleBuffer != nil {
if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer), let dataProvider = CGDataProvider(data: imageData as CFData), let cgImageRef = CGImage(jpegDataProviderSource: dataProvider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
{
var image: UIImage
if (self.isLandscapeLeft || self.isLandscapeRight)
{
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: self.isLandscapeLeft ? UIImageOrientation.left : UIImageOrientation.right)
} else {
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: self.isPortrait ? UIImageOrientation.up : UIImageOrientation.down)
}
image = self.fixOrientation(img: image)
self.images.append(image)
DispatchQueue.main.async {
self.imagePreviews.reloadData()
}
}
}
})
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let connection = self.videoPreviewLayer?.connection {
let currentDevice: UIDevice = UIDevice.current
let orientation: UIDeviceOrientation = currentDevice.orientation
let previewLayerConnection : AVCaptureConnection = connection
if (previewLayerConnection.isVideoOrientationSupported) {
switch (orientation) {
case .portrait:
isLandscapeLeft = false
isLandscapeRight = false
isPortrait = true
isPortraitUpsideDown = false
updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)
break
case .landscapeRight:
isLandscapeLeft = false
isLandscapeRight = true
isPortrait = false
isPortraitUpsideDown = false
updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeRight)
break
case .landscapeLeft:
isLandscapeLeft = true
isLandscapeRight = false
isPortrait = false
isPortraitUpsideDown = false
updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeLeft)
break
case .portraitUpsideDown:
isLandscapeLeft = false
isLandscapeRight = false
isPortrait = false
isPortraitUpsideDown = true
updatePreviewLayer(layer: previewLayerConnection, orientation: .portraitUpsideDown)
break
default:
updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)
break
}
}
}
}
func fixOrientation(img: UIImage) -> UIImage {
if (img.imageOrientation == .up) {
return img
}
UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
img.draw(in: rect)
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return normalizedImage
}
最佳答案
从纵向设备创建图像时,您应该考虑将 UIImage 旋转 90 度,例如:
switch UIApplication.shared.statusBarOrientation {
case .portrait:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .right)
case .landscapeRight:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .up)
case .landscapeLeft:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .down)
case .portraitUpsideDown:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .left)
default:
fatalError("Unexpected orientation")
}
有关完整示例,请参阅:
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var videoPreviewView: UIView!
var videoPreviewLayer: AVCaptureVideoPreviewLayer!
var session: AVCaptureSession = AVCaptureSession()
var stillImageOutput: AVCaptureStillImageOutput = {
let output = AVCaptureStillImageOutput()
output.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
return output
}()
var images: [UIImage] = [UIImage]()
var orientation = UIApplication.shared.statusBarOrientation
override func viewDidLoad() {
super.viewDidLoad()
guard let device = AVCaptureDevice.default(for: .video) else {
print("Unable to create capture device")
return
}
let input: AVCaptureDeviceInput
do {
input = try AVCaptureDeviceInput(device: device)
} catch {
print("Unable to create input", error)
return
}
guard session.canAddInput(input) else {
print("Cannot add input")
return
}
session.addInput(input)
guard session.canAddOutput(stillImageOutput) else {
print("Cannot add output")
return
}
session.addOutput(stillImageOutput)
session.startRunning()
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
videoPreviewView.layer.addSublayer(videoPreviewLayer)
}
@IBAction func didTapCaptureButton(_ sender: Any) {
if let connection = stillImageOutput.connection(with: .video) {
stillImageOutput.captureStillImageAsynchronously(from: connection) { sampleBuffer, error in
guard let sampleBuffer = sampleBuffer, error == nil else {
print(error ?? "Unknown error")
return
}
guard
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer),
let dataProvider = CGDataProvider(data: imageData as CFData),
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) else {
print("unable to capture image")
return
}
var image: UIImage?
switch self.orientation {
case .portrait:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .right)
case .landscapeRight:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .up)
case .landscapeLeft:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .down)
case .portraitUpsideDown:
image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: .left)
default:
fatalError("Unexpected orientation")
}
guard image != nil else {
print("unable to create UIImage")
return
}
DispatchQueue.main.async {
self.images.append(image!)
self.imageView.image = image
}
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let connection = self.videoPreviewLayer?.connection {
orientation = UIApplication.shared.statusBarOrientation
switch orientation {
case .portrait: updatePreviewOrientation(for: connection, to: .portrait)
case .landscapeRight: updatePreviewOrientation(for: connection, to: .landscapeRight)
case .landscapeLeft: updatePreviewOrientation(for: connection, to: .landscapeLeft)
case .portraitUpsideDown: updatePreviewOrientation(for: connection, to: .portraitUpsideDown)
default: updatePreviewOrientation(for: connection, to: .portrait)
}
}
}
private func updatePreviewOrientation(for connection: AVCaptureConnection, to orientation: AVCaptureVideoOrientation) {
if connection.isVideoOrientationSupported {
connection.videoOrientation = orientation
}
videoPreviewLayer.frame = videoPreviewView.bounds
}
}
您正在 fixOrientation 中手动转换图像方向。使用适当的 orientation 从 CGImage 创建 UIImage 后,如果您不想要,就不必重新创建图像.
关于ios - AVCAPTURE 图像方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46913953/
这里有一个很好的答案解释了如何在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返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
我正在尝试使用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
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
有这样的事吗?我想在Ruby程序中使用它。 最佳答案 试试这个http://csl.sublevel3.org/jp2a/此外,Imagemagick可能还有一些东西 关于ruby-是否有将图像文件转换为ASCII艺术的命令行程序或库?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/6510445/
我正在使用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
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
我对图像处理完全陌生。我对JPEG内部是什么以及它是如何工作一无所知。我想知道,是否可以在某处找到执行以下简单操作的ruby代码:打开jpeg文件。遍历每个像素并将其颜色设置为fx绿色。将结果写入另一个文件。我对如何使用ruby-vips库实现这一点特别感兴趣https://github.com/ender672/ruby-vips我的目标-学习如何使用ruby-vips执行基本的图像处理操作(Gamma校正、亮度、色调……)任何指向比“helloworld”更复杂的工作示例的链接——比如ruby-vips的github页面上的链接,我们将不胜感激!如果有ruby-