把一张图片压缩并截取中间部分

//这个方法是把一张UIImage压缩成newSize的尺寸

-(UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize

{

    UIGraphicsBeginImageContext(newSize);

    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

 

/*******截取中间部分*******/

- (UIImage *)scaleImage:(UIImage *)image toScale:(CGSize)reSize

{

    //先按要显示的大小去比例缩放下图片,这里压缩成245*245的大小

    UIImage *scaledImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(245, 245)];

    //计算截取位置。这里我们考虑一般拍照边界位置可能存在全白或全黑的情况,多数重要的会在中间位置。所以计算下截取是重绘图片的中间位置

    float drawW = 0.0;

    float drawH = 0.0;

    CGSize size_new = scaledImage.size;

    if (size_new.width > reSize.width) {

        drawW = (size_new.width - reSize.width)/2.0;

    }

    if (size_new.height > reSize.height) {

        drawH = (size_new.height - reSize.height)/2.0;

    }

    NSLog(@"drawW=====w==%f\n--------drawH==%f\n\n",drawW,drawH);    

    //截取截取大小为需要显示的大小。取图片中间位置截取

    CGRect myImageRect = CGRectMake(drawW, drawH, reSize.width, reSize.height);

    UIImage* bigImage= scaledImage;

    scaledImage = nil;

    CGImageRef imageRef = bigImage.CGImage;

    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);

    

    UIGraphicsBeginImageContext(reSize);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextDrawImage(context, myImageRect, subImageRef);

    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];

    UIGraphicsEndImageContext();

    CGImageRelease(subImageRef);

    return smallImage;

}

转载于:https://www.cnblogs.com/xiaobaizhu/archive/2013/06/05/3120009.html

你可能感兴趣的:(把一张图片压缩并截取中间部分)