objective-c - iOS从nsdata压缩图片

标签 objective-c ios uiimage jpeg nsdata

我有一个下载 jpeg 图像的应用程序,但它们很大,比应用程序所需的大。我创建了一个将下载图像的 NSData 的类。获取 NSData 并压缩图像的最佳方法是什么。

到目前为止,我看到的唯一途径是将图像临时写入磁盘,访问它并在磁盘上压缩 jpeg。

有没有另一种方法,您不必写入磁盘并直接压缩它并接收数据?

最佳答案

最好在您的应用程序下载之前压缩图像。但是,如果这超出了您的控制范围,请在之后压缩它们。

要将图像转换为另一种格式,您可以使用 CGImageDestination.h 中定义的函数

我会制作一个转换给定图像的类方法的函数:

+ (NSData*)imageDataWithCGImage:(CGImageRef)CGimage UTType:(const CFStringRef)imageUTType desiredCompressionQuality:(CGFloat)desiredCompressionQuality
{
    NSData* result = nil;

    CFMutableDataRef destinationData = CFDataCreateMutable(kCFAllocatorDefault, 0);
    CGImageDestinationRef destinationRef = CGImageDestinationCreateWithData(destinationData, imageUTType, 1, NULL);
    CGImageDestinationSetProperties(destinationRef, (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:desiredCompressionQuality], (NSString*)kCGImageDestinationLossyCompressionQuality, nil]);
    if (destinationRef != NULL)
    {
        CGImageDestinationAddImage(destinationRef, CGimage, NULL);

        if (CGImageDestinationFinalize(destinationRef))
        {
            result = [NSData dataWithData:(NSData*)destinationData];
        }
    }
    if (destinationData)
    {
        CFRelease(destinationData);
    }
    if (destinationRef)
    {
        CFRelease(destinationRef);
    }
    return result;
}

图像类型可以是 kUTTypePNG,但质量参数很可能不起作用。它也可以是 kUTTypeJPEG2000 以满足您的需要。

您可以使用数据初始化新图像或将其保存到磁盘。

关于objective-c - iOS从nsdata压缩图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408841/

相关文章:

iOS - 将图像裁剪到检测到的面部时出现问题

ios - 为什么在关闭 View Controller 时不循环保留(非圆弧)

iphone - 如何为可拉伸(stretch)的 UIImage 着色

ios - 找不到有关 forTraitCollection 的苹果文档

android - 开源用户安全/密码方案

swift - 在 SCNNode/ARKit Swift 中获取图像大小

iphone - 在我的 iPhone 应用程序中调用 rss

c++ - 我可以同时连接到多个蓝牙 HCI 吗?

ios - 将 PFObject 分配给 UILabel - 将 PFUser 转换为 NSString 值?

ios - 在 Swift 中使用带有 IBOutlet 的 UIImageView 在 Interface Builder 中查看它