iOS-比例压缩图片


// 1600 * 1200
-(NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize{

    //调整分辨率
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = 0.0f;
    CGFloat tempWidth = 0.0f;
    CGFloat rate = newSize.width / newSize.height;
    
    if (rate < 1) {
        tempHeight = newSize.height / 1600;
        tempWidth = newSize.width / 1200;
    } else {
        tempHeight = newSize.height / 1200;
        tempWidth = newSize.width / 1600;
    }
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
        
    }else if (tempWidth > 1.0 && tempWidth == tempHeight){
        
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
        
    }
    
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSLog(@"sourceImageW = %f sourceImageH = %f",source_image.size.width, source_image.size.height);
    NSLog(@"newImageW = %f newImageH = %f",newImage.size.width,newImage.size.height);
    
    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
    NSUInteger sizeOrigin = [imageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    NSLog(@"--->sizeOriginKB:%lu<----",sizeOriginKB);
    
    if (sizeOriginKB > maxSize) {
        
        float kk = 1.0;
        NSUInteger zipSizeKB;
        float aa = 0.1f;// 变化系数
        zipSizeKB = UIImageJPEGRepresentation(newImage, kk).length / 1024;
        
        
        while (zipSizeKB > maxSize) {
            
            @autoreleasepool {
                if (kk>aa) {
                    kk-=aa;
                    if (zipSizeKB == UIImageJPEGRepresentation(newImage, kk).length / 1024) {
                        break;
                    }
                    zipSizeKB = UIImageJPEGRepresentation(newImage, kk).length / 1024 ;
                }
            }
        }
        
        return UIImageJPEGRepresentation(newImage, kk);
    }
    
    return imageData;

}

你可能感兴趣的:(iOS-比例压缩图片)