IOS 图片压缩保存

创建一个UIImage+Category用于压缩图片处理
/**
 *  @brief 压缩照片
 *  @parma img:目标图片
 *  @parma newSize:压缩至目标尺寸
 */
-(UIImage *)compressImageWithImage:(UIImage *)img scaleToSize:(CGSize)newsize
{
    UIGraphicsBeginImageContext(newsize);
//    [img drawInRect:CGRectMake(0, 0,newsize.width, newsize.height)];
    [img drawInRect:CGRectMake(0, 0,newsize.width + 1, newsize.height) blendMode:kCGBlendModeLuminosity alpha:1];
    UIImage *resImge = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resImge;
}

/**
 *  @brief 保存至相册
 *  @parma newSize:压缩至目标尺寸
 */
-(void)saveImageToAlbumWithImage:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, nil, @selector(saveSuccess), nil);
}

在需要压缩图片的地方使用:

//压缩图片
- (UIImage *) saveImage:(UIImage *)currentImage{
    
    NSData *imgaData = UIImageJPEGRepresentation(currentImage, 1);
    if (imgaData == nil) {
        return nil;
    }
    float imageSize = imgaData.length/1024.0;
    if(imageSize < 300)
    {
        return currentImage;
    }else{
        //300为300k得到需要缩小的倍数关系传入宽高比进项压缩
        CGFloat imgWidth = currentImage.size.width/sqrtf(imageSize/300);
        CGFloat imgHeight = currentImage.size.height/sqrtf(imageSize/300);
        UIImage *resImage = [currentImage compressImageWithImage:currentImage scaleToSize:CGSizeMake(imgWidth, imgHeight)];
        return resImage;
    }
}




你可能感兴趣的:(ios开发)