iphone 压缩图片到指定的大小

1.本文摘自:http://www.cocoachina.com/bbs/read.php?tid-20940.html

 

  1. #import <Foundation/Foundation.h>
  2. @interface UIImage (UIImageExt)
  3. - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;
  4. @end



复制代码
  1. #import "UIImageExt.h"
  2. @implementation UIImage (UIImageExt)
  3. - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
  4. {
  5.     UIImage *sourceImage = self;
  6.     UIImage *newImage = nil;      
  7.     CGSize imageSize = sourceImage.size;
  8.     CGFloat width = imageSize.width;
  9.     CGFloat height = imageSize.height;
  10.     CGFloat targetWidth = targetSize.width;
  11.     CGFloat targetHeight = targetSize.height;
  12.     CGFloat scaleFactor = 0.0;
  13.     CGFloat scaledWidth = targetWidth;
  14.     CGFloat scaledHeight = targetHeight;
  15.     CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
  16.     
  17.     if (CGSizeEqualToSize(imageSize, targetSize) == NO)
  18.     {
  19.         CGFloat widthFactor = targetWidth / width;
  20.         CGFloat heightFactor = targetHeight / height;
  21.         
  22.         if (widthFactor > heightFactor)
  23.             scaleFactor = widthFactor; // scale to fit height
  24.         else
  25.             scaleFactor = heightFactor; // scale to fit width
  26.         scaledWidth  = width * scaleFactor;
  27.         scaledHeight = height * scaleFactor;
  28.         
  29.         // center the image
  30.         if (widthFactor > heightFactor)
  31.         {
  32.             thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
  33.         }
  34.         else
  35.             if (widthFactor < heightFactor)
  36.             {
  37.                 thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
  38.             }
  39.     }      
  40.     
  41.     UIGraphicsBeginImageContext(targetSize); // this will crop
  42.     
  43.     CGRect thumbnailRect = CGRectZero;
  44.     thumbnailRect.origin = thumbnailPoint;
  45.     thumbnailRect.size.width  = scaledWidth;
  46.     thumbnailRect.size.height = scaledHeight;
  47.     
  48.     [sourceImage drawInRect:thumbnailRect];
  49.     
  50.     newImage = UIGraphicsGetImageFromCurrentImageContext();
  51.     if(newImage == nil)
  52.         NSLog(@"could not scale image");
  53.     
  54.     //pop the context to get back to the default
  55.     UIGraphicsEndImageContext();
  56.     return newImage;
  57. }
  58. @end
 

你可能感兴趣的:(iPhone)