简体   繁体   English

从NSData创建Jpeg

[英]Create Jpeg from NSData

I am getting images from sever using this : 我使用这个从服务器获取图像:

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (!error)
         {
             completionBlock(YES, data);
         }
         else
         {
             completionBlock(NO, nil);
         }
     }];
}

Which provide me NSData . 哪个提供NSData。 Now for better performance i would like to present the image in jpeg . 现在为了更好的性能,我想在jpeg呈现图像。

I know how to convert NSData to UIImag e, with UIImage *image=[UIImage imageWithData:data]; 我知道如何使用UIImage *image=[UIImage imageWithData:data];NSData to UIImag转换NSData to UIImag e UIImage *image=[UIImage imageWithData:data]; And how to create NSData from image NSData *imageData = UIImagePNGRepresentation(image); 以及如何从图像NSData *imageData = UIImagePNGRepresentation(image);创建NSData NSData *imageData = UIImagePNGRepresentation(image);

But both are not do what i need, i would like to take that NSData i get from the server, and create out of it JPEG image . 但两者都没有做我需要的,我想从服务器获取NSData,并创建它的JPEG图像。 how would i do that ? 我该怎么办? (do i have to create first a new data with jpeg ,than the image from this data? ) (我是否必须首先使用jpeg创建一个数据,而不是来自此数据的图像?)

To convert the data you get from the server to jpeg, use: 要将从服务器获取的数据转换为jpeg,请使用:

UIImage *image = [UIImage imageWithData:serverData];
NSData *jpegData = UIImageJPEGRepresentation(image, 0.75f);

you need to probably do something like this: 你需要做这样的事情:

CGDataProviderRef imgProvider = CGDataProviderCreateWithCFData((CFDataRef) data);
CGImageRef imgRef = CGImageCreateWithJPEGDataProvider(imgProvider, NULL, true, kCGRenderingIntentDefault);

make sure to release imgRef and imgProvider 确保释放imgRef和imgProvider

With Swift 5 and iOS 12, you can use CGImage , CGImageDestination and CGDataProvider in order to convert some image data. 使用Swift 5和iOS 12,您可以使用CGImageCGImageDestinationCGDataProvider来转换一些图像数据。 The following function implementation shows how to do so: 以下函数实现说明了如何执行此操作:

import Foundation
import ImageIO
import MobileCoreServices

func convertImageData(_ data: Data) -> Data? {
    guard let provider = CGDataProvider(data: data as CFData) else {
        print("Could not create data provider from data")
        return nil
    }

    guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
        print("Could not create cgImage from provider")
        return nil
    }

    let data = NSMutableData()
    guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, kUTTypeJPEG, 1, nil) else {
        print("Could not create an image destination from url")
        return nil
    }

    let options = [
        kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
        kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
    ] as CFDictionary

    CGImageDestinationAddImage(imageDestination, cgImage, options)
    let imageIsWritten = CGImageDestinationFinalize(imageDestination)

    if !imageIsWritten {
        print("Image could not be written")
        return nil
    }

    return data as Data
}

Usage: 用法:

let data: Data = …
let newData = convertImageData(data)

As an alternative, you can use CGImage , CGImageDestination and CGDataProvider in order to write some JPEG image data to a given URL . 作为替代方案,您可以使用CGImageCGImageDestinationCGDataProvider将一些JPEG图像数据写入给定的URL The following function implementation shows how to do so: 以下函数实现说明了如何执行此操作:

import Foundation
import ImageIO
import MobileCoreServices

func saveImageData(_ data: Data, to fileUrl: URL) {
    guard let provider = CGDataProvider(data: data as CFData) else {
        print("Could not create data provider from data")
        return
    }

    guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
        print("Could not create cgImage from provider")
        return
    }

    guard let imageDestination = CGImageDestinationCreateWithURL(fileUrl as CFURL, kUTTypeJPEG, 1, nil) else {
        print("Could not create an image destination from url")
        return
    }

    let options = [
        kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
        kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
    ] as CFDictionary

    CGImageDestinationAddImage(imageDestination, cgImage, options)
    let imageIsWritten = CGImageDestinationFinalize(imageDestination)

    if !imageIsWritten {
        print("Image could not be written")
    }
}

Usage: 用法:

let data: Data = …
let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileUrl = documentDirectoryUrl.appendingPathComponent("image.jpeg")
saveImageData(data, to: fileUrl)

Sources: 资料来源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM