UIImage+resize.m 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // UIImage+resize.m
  3. // test23
  4. //
  5. // Created by apple on 15/12/1.
  6. // Copyright (c) 2015年 JCZ. All rights reserved.
  7. //
  8. #import "UIImage+resize.h"
  9. @implementation UIImage(resize)
  10. //将JPEG格式转换为PNG
  11. -(UIImage *)reduceImage:(UIImage *)image percent:(float)percent
  12. {
  13. NSData *imageData = UIImageJPEGRepresentation(image, percent);
  14. UIImage *newImage = [UIImage imageWithData:imageData];
  15. return newImage;
  16. }
  17. //压缩图片尺寸
  18. - (UIImage *)scaledToSize:(CGSize)newSize
  19. {
  20. //首先要找到缩放比 按长的适配 不足的部分空白
  21. CGFloat rate =newSize.width*1.0/ self.size.width ;
  22. if (self.size.height* rate > newSize.height) {
  23. //过长了。
  24. rate =newSize.height*1.0/ self.size.height ;
  25. }
  26. CGSize size = CGSizeMake(self.size.width*rate, self.size.height*rate);
  27. // Create a graphics image context
  28. UIGraphicsBeginImageContext(size);
  29. // new size
  30. [self drawInRect:CGRectMake(0,0,size.width,size.height)];
  31. // Get the new image from the context
  32. UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  33. // End the context
  34. UIGraphicsEndImageContext();
  35. // Return the new image.
  36. return newImage;
  37. }
  38. - (UIImage *)scaledAndCutToSize:(CGSize)newSize{
  39. //首先要找到缩放比 按短的适配 长的部分裁减掉
  40. CGFloat rate =newSize.width*1.0/ self.size.width ;
  41. if (self.size.height* rate < newSize.height) {
  42. //过长了。
  43. rate =newSize.height*1.0/ self.size.height ;
  44. }
  45. CGSize size = CGSizeMake(self.size.width*rate, self.size.height*rate);
  46. UIGraphicsBeginImageContext(size);
  47. [self drawInRect:CGRectMake(0,0,size.width,size.height)];
  48. // Get the new image from the context
  49. UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  50. // End the context
  51. UIGraphicsEndImageContext();
  52. // Return the new image.
  53. return newImage;
  54. }
  55. @end