图像压缩成指定大小(高度/宽度)

来源:互联网 发布:下载站系统源码 编辑:程序博客网 时间:2024/05/01 02:00
复制代码
  1. #import
  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.     CGSizeimageSize = sourceImage.size;
  8.     CGFloatwidth = imageSize.width;
  9.     CGFloatheight = imageSize.height;
  10.     CGFloattargetWidth = targetSize.width;
  11.     CGFloattargetHeight = targetSize.height;
  12.     CGFloatscaleFactor = 0.0;
  13.     CGFloatscaledWidth = targetWidth;
  14.     CGFloatscaledHeight = targetHeight;
  15.     CGPointthumbnailPoint = CGPointMake(0.0,0.0);
  16.     
  17.     if(CGSizeEqualToSize(imageSize, targetSize) == NO)
  18.     {
  19.         CGFloatwidthFactor = targetWidth / width;
  20.         CGFloatheightFactor = 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.     CGRectthumbnailRect = CGRectZero;
  44.     thumbnailRect.origin= thumbnailPoint;
  45.     thumbnailRect.size.width  =scaledWidth;
  46.     thumbnailRect.size.height= scaledHeight;
  47.     
  48.     [sourceImagedrawInRect:thumbnailRect];
  49.     
  50.     newImage= UIGraphicsGetImageFromCurrentImageContext();
  51.     if(newImage== nil)
  52.         NSLog(@"couldnot scale image");
  53.     
  54.     //popthe context to get back to the default
  55.     UIGraphicsEndImageContext();
  56.     returnnewImage;
  57. }
  58. @end



1、创建UIImage的类别,添加图像压缩指定大小方法imageByScalingAndCroppingForSize:(CGSize)targetSize;此方法传入一个压缩图像大小以后的高度和宽度。(第一部分代码)
2、实现UIImageExt类别,初始化图像缩放默认值。(9-19)
3、然后检查是否需要进行图像缩放。(21)
4、如果需要缩放,则计算先分别计算高度、宽度的因子。(23-24)
5、选择因子系数最大的一边作为图像的缩放因子。(26-29)
6、根据前面得到的图像缩放因子得到缩放图像的等比例高度和宽度值。(30-31)
7、由于是按照最大系数一边进行缩放,造成其中另外一边会出现空白,所以需要计算出另外一边居中显示的坐标值。(34-42)
8、最后根据最新合成的Origin和Size在画布完成内容绘制。(45-52)
9、保存为UIImage对象。(54-56)
10、关闭画图,返回UIImage对象。(59-60) 


0 0