我是如何压缩图片的?ios开发必用的一个技巧。

- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");

    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


+ (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength{


    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    while (data.length > maxLength && compression > 0.000001) {
        if (data.length*1.0/maxLength>=2) {
            CGFloat scale = data.length/maxLength;

            UIImage *cureeimage = [UIImage imageWithData:data];
            CGSize scalesize = CGSizeMake(cureeimage.size.width/scale, cureeimage.size.height/scale);
            UIImage *sizeimage = [cureeimage imageByScalingAndCroppingForSize:scalesize  ];
            compression =1;
            image = sizeimage;
        }else if (data.length*1.0/maxLength>=1.5){
            compression /=1.5;
        }else{
            compression /=1.2;
        }
        data = UIImageJPEGRepresentation(image, compression); // When compression less than a value, this code dose not work
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (resultImage!=nil) {
        return resultImage;
    }else{
        return image;
    }

    return resultImage;
}

你可能感兴趣的:(我是如何压缩图片的?ios开发必用的一个技巧。)