给定CIImage,将图像数据写入磁盘的最快方法是什么? [英] Given a CIImage, what is the fastest way to write image data to disk?

查看:140
本文介绍了给定CIImage,将图像数据写入磁盘的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PhotoKit,并且已实现滤镜,用户可以将滤镜应用于其照片库中的照片.我当前正在获取图像,应用过滤器,将编辑后的版本作为CIImage返回,然后使用UIImageJPEGRepresentationCIImage转换为NSData,因此可以将其写到磁盘上.尽管这样做效果很好,但是当用户尝试编辑非常大的照片(如30 MB)时,最多可能需要30秒才能完成,而98%的时间都花在了UIImageJPEGRepresentation上(从Instruments获得的数据).

I'm working with PhotoKit and have implemented filters users can apply to photos in their Photo Library. I am currently obtaining the image, applying a filter, returning the edited version as a CIImage, then I convert the CIImage into NSData using UIImageJPEGRepresentation so I may write that out to disk. While this works beautifully, when users attempt to edit really large (like 30 MB) photos it can take upwards of 30 seconds for this to occur, with 98% of the time spent on UIImageJPEGRepresentation (stat obtained from Instruments).

我正在寻找一种更有效的方法来将编辑后的照片保存到磁盘上,并且尽可能不降低质量.

I am looking for a more efficient way to save this edited photo to disk without compromising quality, if possible.

我知道UIImagePNGRepresentation可能会提高质量,但这比JPEG表示还要慢.

I understand UIImagePNGRepresentation may result in improved quality, but this is even slower than the JPEG representation.

这是我当前正在默认优先级线程(qos_class_utility)上执行的操作:

This is what I am currently doing, on the default priority thread (qos_class_utility):

func jpegRepresentationOfImage(image: CIImage) -> NSData {
    let eaglContext = EAGLContext(API: .OpenGLES2)
    let ciContext = CIContext(EAGLContext: eaglContext)

    let outputImageRef = ciContext.createCGImage(image, fromRect: image.extent())
    let uiImage = UIImage(CGImage: outputImageRef, scale: 1.0, orientation: UIImageOrientation.Up)

    return UIImageJPEGRepresentation(uiImage, 0.9) //this takes upwards of 20-30 seconds with large photos!
}

//writing out to disk:
var error: NSError?
let success = jpegData.writeToURL(contentEditingOutput.renderedContentURL, options: NSDataWritingOptions.AtomicWrite, error: &error)

推荐答案

我建议使用CGImageDestination将CGImage直接传递给ImageIO.您可以将字典传递给CGImageDestinationAddImage,以指示压缩质量,图像方向等.

I would suggest passing the CGImage directly to ImageIO using CGImageDestination. You can pass a dictionary to CGImageDestinationAddImage to indicate the compression quality, image orientation, etc.

CFDataRef save_cgimage_to_jpeg (CGImageRef image)
{
    CFMutableDataRef cfdata = CFDataCreateMutable(nil,0);
    CGImageDestinationRef dest = CGImageDestinationCreateWithData(data, CFSTR("public.jpeg"), 1, NULL);
    CGImageDestinationAddImage(dest, image, NULL);
    if(!CGImageDestinationFinalize(dest))
        ; // error
    CFRelease(dest);
    return cfdata
}

这篇关于给定CIImage,将图像数据写入磁盘的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆