码迷,mamicode.com
首页 > 其他好文 > 详细

图片压缩裁剪

时间:2015-04-15 17:20:59      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

-(UIImage*)scalingAndCroppingImage:(UIImage*)sourceImage forSize:(CGSize)size
{
    UIImage *newImage = sourceImage;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat img_W = imageSize.width;
    
    CGFloat img_H= imageSize.height;
    
    CGFloat bound_W = size.width;
    
    CGFloat bound_H = size.height;
  
    bound_W = bound_W *SCREENSCALE;
    bound_H = bound_H *SCREENSCALE;
    CGFloat scaleFactor = 0.0;
    
    CGFloat scaled_W = bound_W;
    
    CGFloat scaled_H= bound_H;
    
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    CGFloat widthFactor = bound_W / img_W;
    
    CGFloat heightFactor = bound_H / img_H;
    
    if (widthFactor > heightFactor)
        
        scaleFactor = widthFactor; // scale to fit height
    
    else
        
        scaleFactor = heightFactor; // scale to fit width
    
    
    scaled_W= img_W * scaleFactor;
    
    scaled_H = img_H * scaleFactor;
    
    // center the image
    
    if (widthFactor > heightFactor)
        
    {
        
        thumbnailPoint.y = (scaled_H - bound_H) * 0.5;
        
    }
    
    else if (widthFactor < heightFactor)
        
    {
        
        thumbnailPoint.x = (scaled_W - bound_W) * 0.5;
        
    }
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.size.width= bound_W;
    
    thumbnailRect.size.height = bound_H;
    if (img_H>=bound_H&&img_W>=bound_W) {
        thumbnailRect.origin = thumbnailPoint;
        newImage = [self compressImage:sourceImage withSize:CGSizeMake(scaled_W, scaled_H)];
    }else{
        thumbnailRect.origin.x = (img_W-bound_W)/2;
        thumbnailRect.origin.y = (img_H-bound_H)/2;
    }
    CGImageRef cgimg = CGImageCreateWithImageInRect([newImage CGImage],thumbnailRect);
    newImage = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);
   
    return newImage;
    
}
- (UIImage *)compressImage:(UIImage *)imgSrc withSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    CGRect rect = {{0,0}, size};
    [imgSrc drawInRect:rect];
    UIImage *compressedImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return compressedImg;
}


图片压缩裁剪

标签:

原文地址:http://my.oschina.net/u/2330410/blog/401890

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!