업로드 서버 이미지의 크기를 어떻게 제한합니까

1987 단어
// 
    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;
}

좋은 웹페이지 즐겨찾기