关闭

压缩图片尺寸

标签: ios压缩图片
113人阅读 评论(0) 收藏 举报
分类:

//
  // UIImage+SuperCompress.m
  // JKCategories (https://github.com/shaojiankui/JKCategories)
  //
  // Created by Jakey on 16/1/22.
  // Copyright © 2016年 Jakey. All rights reserved.
  //
   
  #import "UIImage+JKSuperCompress.h"
   
  @implementation UIImage (JKSuperCompress)
  + (UIImage*)jk_resizableHalfImage:(NSString *)name
  {
  UIImage *normal = [UIImageimageNamed:name];
   
  CGFloat imageW = normal.size.width *0.5;
  CGFloat imageH = normal.size.height *0.5;
  return [normalresizableImageWithCapInsets:UIEdgeInsetsMake(imageH, imageW, imageH, imageW)];
  }
   
   
  + (NSData *)jk_compressImage:(UIImage *)imagetoMaxLength:(NSInteger)maxLengthmaxWidth:(NSInteger)maxWidth{
  NSAssert(maxLength > 0, @"图片的大小必须大于 0");
  NSAssert(maxWidth > 0, @"图片的最大边长必须大于 0");
   
  CGSize newSize = [selfjk_scaleImage:image withLength:maxWidth];
  UIImage *newImage = [selfjk_resizeImage:image withNewSize:newSize];
   
  CGFloat compress = 0.9f;
  NSData *data = UIImageJPEGRepresentation(newImage, compress);
   
  while (data.length > maxLength && compress >0.01) {
  compress -= 0.02f;
   
  data = UIImageJPEGRepresentation(newImage, compress);
  }
  return data;
  }
   
  + (UIImage *)jk_resizeImage:(UIImage *)image withNewSize:(CGSize)newSize{
   
  UIGraphicsBeginImageContext(newSize);
  [image drawInRect:CGRectMake(0,0, newSize.width, newSize.height)];
   
  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
   
  return newImage;
  }
   
  + (CGSize)jk_scaleImage:(UIImage *)image withLength:(CGFloat)imageLength{
   
  CGFloat newWidth = 0.0f;
  CGFloat newHeight = 0.0f;
  CGFloat width = image.size.width;
  CGFloat height = image.size.height;
   
  if (width > imageLength || height > imageLength){
   
  if (width > height) {
   
  newWidth = imageLength;
  newHeight = newWidth * height / width;
   
  }else if(height > width){
   
  newHeight = imageLength;
  newWidth = newHeight * width / height;
   
  }else{
   
  newWidth = imageLength;
  newHeight = imageLength;
  }
   
  }else{
  return CGSizeMake(width, height);
  }
   
  return CGSizeMake(newWidth, newHeight);
  }
   
  @end
今天在群里面学习了,如何压缩图片,具体的代码如上,希望对各位有用!

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9842次
    • 积分:141
    • 等级:
    • 排名:千里之外
    • 原创:0篇
    • 转载:24篇
    • 译文:0篇
    • 评论:1条
    文章分类
    文章存档
    最新评论