如何限制上传服务器图片的大小

//获得原始图片的大小
    UIImage * image = [UIImage imageNamed:@"qixie"];
    NSData * imageData=UIImagePNGRepresentation(image);
    NSLog(@"原始图片的大小---->%lu",[imageData length]);

//第一个参数为分辨率 ,第二个参数为限制图片的大小
    NSData * imgData = [self reSizeImageData:image maxImageSize:1024 maxSizeWithKB:200];

/**
 *  调整图片尺寸和大小
 *
 *  @param sourceImage  原始图片
 *  @param maxImageSize 新图片最大尺寸
 *  @param maxSize      新图片最大存储大小
 *
 *  @return 新图片imageData
 */
- (NSData *)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize maxSizeWithKB:(CGFloat) maxSize
{
    //当没有进行设置数值的时候,初始化默认的分辨率和最大压缩后的大小
    if (maxSize <= 0.0)
    {
        maxSize = 1024;
    }
    if (maxImageSize <= 0.0)
    {
        maxImageSize = 200;
    }
    
    //先调整分辨率
    CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
    
    CGFloat tempHeight = newSize.height / maxImageSize;
    CGFloat tempWidth = newSize.width / maxImageSize;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
    CGFloat sizeOriginKB = imageData.length / 1024.0;
    
    CGFloat resizeRate = 0.9;
    while (sizeOriginKB > maxSize && resizeRate > 0.1) {
        imageData = UIImageJPEGRepresentation(newImage,resizeRate);
        sizeOriginKB = imageData.length / 1024.0;
        resizeRate -= 0.1;
    }
    NSLog(@"图片的大小-----%lu",(unsigned long)imageData.length);
    return imageData;
}

你可能感兴趣的:(如何限制上传服务器图片的大小)