ios 对图片进行压缩

点击查看
https://segmentfault.com/q/1010000000701850

http://www.3lian.com/edu/2015/05-30/217852.html

两种改变图片的方式

// 通过改变像素点改变体积
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
}

// 通过改变图片体积改变图片大小
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGFloat)newSize
{
    CGFloat W = image.size.width;
    CGFloat H = image.size.height;
    CGFloat scaleFactorW = newSize / W;
    CGFloat scaleFactorH = newSize / H;
    CGFloat scaleFactor = MIN(scaleFactorH, scaleFactorW);
    CGFloat newW = W * scaleFactor;
    CGFloat newH = H * scaleFactor;
    
    if (W < newSize || H < newSize) {
        return image;
    }
 
    CGSize size = CGSizeMake(newW, newH);
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

你可能感兴趣的:(ios 对图片进行压缩)