我想将NSImage转换为mp4

时间:2016-01-16 16:19:17

标签: swift nsimage cgimage

Adam Jensen做了一个出色的工作@制作一些快速代码将图像转换为mov。

https://gist.github.com/acj/6ae90aa1ebb8cad6b47b

上述功能非常好,但是我想使用比一般iPad略多CPU和一些真实存储的设备来完成这项工作,所以我需要在OS X下运行。说起来容易做起来难。

首先,我没有得到UIKit,取而代之的是Cocoa。 没有UIImage,取而代之的是NSImage。 在黑暗的修正中做一些刺伤;固定/跳过减少31个错误降低到5.但我需要一些帮助。

func fillPixelBufferFromImage(image: NSImage, pixelBuffer: CVPixelBuffer, contentMode:UIViewContentMode){

CVPixelBufferLockBaseAddress(pixelBuffer, 0)

let data = CVPixelBufferGetBaseAddress(pixelBuffer)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGBitmapContextCreate(data, Int(self.outputSize.width), Int(self.outputSize.height), 8, CVPixelBufferGetBytesPerRow(pixelBuffer), rgbColorSpace, CGImageAlphaInfo.PremultipliedFirst.rawValue)

CGContextClearRect(context, CGRectMake(0, 0, CGFloat(self.outputSize.width), CGFloat(self.outputSize.height)))

let horizontalRatio = CGFloat(self.outputSize.width) / image.size.width
let verticalRatio = CGFloat(self.outputSize.height) / image.size.height
var ratio: CGFloat = 1

switch(contentMode) {
case .ScaleAspectFill:
  ratio = max(horizontalRatio, verticalRatio)
case .ScaleAspectFit:
  ratio = min(horizontalRatio, verticalRatio)
default:
  ratio = min(horizontalRatio, verticalRatio)
}

let newSize:CGSize = CGSizeMake(image.size.width * ratio, image.size.height * ratio)

let x = newSize.width < self.outputSize.width ? (self.outputSize.width - newSize.width) / 2 : 0
let y = newSize.height < self.outputSize.height ? (self.outputSize.height - newSize.height) / 2 : 0

CGContextDrawImage(context, CGRectMake(x, y, newSize.width, newSize.height), image.CGImage)

CVPixelBufferUnlockBaseAddress(pixelBuffer, 0)
}

我的CGIImage直接加载了Quartz2D库。

    let realURL = NSURL(string: urlString)
    if let image = CGImageSourceCreateWithURL(realURL!, nil) {
    var pixelBuffer: CVPixelBuffer? = nil
    let status: CVReturn = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pixelBufferAdaptor.pixelBufferPool!, &pixelBuffer)

    if let pixelBuffer = pixelBuffer where status == 0 {
      let managedPixelBuffer = pixelBuffer

但是我需要一些帮助来理解如何提取像素以填充我认为的pixelBuffer。我从哪里开始这样做?

0 个答案:

没有答案