图片的压缩

Posted 我来看烟花

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片的压缩相关的知识,希望对你有一定的参考价值。

图片的压缩其实是俩概念,
1、是 “压” 文件体积变小,但是像素数不变,长宽尺寸不变,那么质量可能下降,
2、是 “缩” 文件的尺寸变小,也就是像素数减少。长宽尺寸变小,文件体积同样会减小。

这个 UIImageJPEGRepresentation(image, 0.0),是1的功能。这个 [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)] 是2的功能。

所以,得结合使用来满足需求,不然你一味的用1,导致,图片模糊的不行,但是尺寸还是很大。

//图片压缩到指定大小
- (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;

以上是关于图片的压缩的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发探索-图片压缩处理

图片的压缩

图片的压缩

Android图片压缩(质量压缩和尺寸压缩)

OpenCV教程(11)-- 图像压缩操作

图片压缩之处理小图片压缩策略