开发者社区> 问答> 正文

ios 对图片进行压缩

我是用这个函数对图片进行压缩的

NSData *fData = UIImageJPEGRepresentation(self.photo, 1.0);
这样,图片是7MB这样。假如压缩级别是0.5,如:

NSData *fData = UIImageJPEGRepresentation(self.photo, 0.5);
图片压缩之后,大小是 1MB左右。。现在问题来了。

一张图片,压缩级别是0.5的话,大小不会变成原来的0.5倍。我算了一下,大概是0.14.所以压缩级别和这个大小好像不能形成一定的关联。

比如我一张 500KB的图片,0.5的压缩级别。大小可能才100多KB。对我来说,正好。但是假如像上面那样,7MB的大小,按照这样的压缩率,就是1MB.所以图片时大时小。对用户来说,体验肯定比较差。

我想动态的压缩图片,让没有wifi的情况下,无论多少大小的图片,压缩之后大小最大 200KB。有wifi,压缩大小最大 700KB。

目前有比较好的算法吗?或者开源的函数。

--------------------------

贴一个相关函数

//图片压缩到指定大小
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
        scaleFactor = widthFactor; // scale to fit height
        else
        scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
    NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

展开
收起
a123456678 2016-07-27 16:07:40 2207 0
1 条回答
写回答
取消 提交回答
  • 第二个参数是压缩系数,他的设置并不能保证图片的大小,因为压缩之后的大小和图片的内容也有关系,比如你的图片的的颜色相似的话压缩之后图片的大小就会小点。你所在在意的wifi情况压缩图片是不是指需要上传呢,如果是需要上传的话你可以压缩两种格式的图片,高质量的和低质量的图片,有wifi的情况下上传高质量的图片,没有wifi的情况下上传低质量的图片

    2019-07-17 20:00:46
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
手淘iOS性能优化探索 立即下载
From Java/Android to Swift iOS 立即下载
深入剖析iOS性能优化 立即下载