将UIimage(拍照)转换为NSData

时间:2015-11-07 08:55:57

标签: image swift

我用这种方法拍照。

func convertImageFromCMSampleBufferRef(sampleBuffer:CMSampleBuffer) -> CIImage{
    let pixelBuffer:CVPixelBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)!;
    let ciImage:CIImage = CIImage(CVPixelBuffer: pixelBuffer)

    if done == true {

        newImage =  UIImage(CIImage:ciImage, scale: CGFloat(1.0), orientation: .DownMirrored)

        var imageData = UIImageJPEGRepresentation(newImage, 0.6)
        var compressedJPGImage = UIImage(data: imageData)
        UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)       
    }

    return ciImage;
}

代码应该有效,但变量imageData = nil 我尝试在PNG中转换图像,但效果相同。

带打印

  

newImage =,{720,1280} imageData = nil

1 个答案:

答案 0 :(得分:6)

你必须将CIImage转换为CGImage,然后将CGImage转换为UIImage,然后将UIImage转换为NSData。

static let context = CIContext(options:nil);
let tempImage:CGImageRef = context.createCGImage(ciImage, fromRect: ciImage.extent())
let image = UIImage(CGImage: tempImage);
let imageData: NSData? = UIImageJPEGRepresentation(image, 0.6);