UIImage+RQExtension.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //
  2. // UIImage+RQExtension.m
  3. // RQCommon
  4. //
  5. // Created by 张嵘 on 2018/11/16.
  6. // Copyright © 2018 张嵘. All rights reserved.
  7. //
  8. #import "UIImage+RQExtension.h"
  9. #import <AVFoundation/AVFoundation.h>
  10. #import <AssetsLibrary/AssetsLibrary.h>
  11. @implementation UIImage (RQExtension)
  12. /**
  13. * 根据图片名返回一张能够自由拉伸的图片 (从中间拉伸)
  14. */
  15. + (UIImage *)rq_resizableImage:(NSString *)imgName
  16. {
  17. UIImage *image = [UIImage imageNamed:imgName];
  18. return [self rq_resizableImage:imgName capInsets:UIEdgeInsetsMake(image.size.height *.5f, image.size.width*.5f, image.size.height*.5f, image.size.width*.5f)];
  19. }
  20. + (UIImage *)rq_resizableImage:(NSString *)imgName capInsets:(UIEdgeInsets)capInsets
  21. {
  22. UIImage *image = [UIImage imageNamed:imgName];
  23. return [image resizableImageWithCapInsets:capInsets];
  24. }
  25. + (UIImage *)rq_imageAlwaysShowOriginalImageWithImageName:(NSString *)imageName
  26. {
  27. UIImage *image = [UIImage imageNamed:imageName];
  28. if ([image respondsToSelector:@selector(imageWithRenderingMode:)])
  29. { //iOS 7.0+
  30. return [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  31. }else{
  32. return image;
  33. }
  34. }
  35. + (UIImage*)rq_thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
  36. AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
  37. NSParameterAssert(asset);
  38. AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
  39. assetImageGenerator.appliesPreferredTrackTransform = YES;
  40. assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
  41. CGImageRef thumbnailImageRef = NULL;
  42. CFTimeInterval thumbnailImageTime = time;
  43. NSError *thumbnailImageGenerationError = nil;
  44. thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
  45. if(!thumbnailImageRef)
  46. NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
  47. UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
  48. return thumbnailImage;
  49. }
  50. /// 获取屏幕截图
  51. ///
  52. /// @return 屏幕截图图像
  53. + (UIImage *)rq_screenShot {
  54. // 1. 获取到窗口
  55. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  56. // 2. 开始上下文
  57. UIGraphicsBeginImageContextWithOptions(window.bounds.size, YES, 0);
  58. // 3. 将 window 中的内容绘制输出到当前上下文
  59. [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO];
  60. // 4. 获取图片
  61. UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
  62. // 5. 关闭上下文
  63. UIGraphicsEndImageContext();
  64. return screenShot;
  65. }
  66. - (UIImage *)rq_fixOrientation {
  67. // No-op if the orientation is already correct
  68. if (self.imageOrientation == UIImageOrientationUp) return self;
  69. // We need to calculate the proper transformation to make the image upright.
  70. // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
  71. CGAffineTransform transform = CGAffineTransformIdentity;
  72. switch (self.imageOrientation) {
  73. case UIImageOrientationDown:
  74. case UIImageOrientationDownMirrored:
  75. transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
  76. transform = CGAffineTransformRotate(transform, M_PI);
  77. break;
  78. case UIImageOrientationLeft:
  79. case UIImageOrientationLeftMirrored:
  80. transform = CGAffineTransformTranslate(transform, self.size.width, 0);
  81. transform = CGAffineTransformRotate(transform, M_PI_2);
  82. break;
  83. case UIImageOrientationRight:
  84. case UIImageOrientationRightMirrored:
  85. transform = CGAffineTransformTranslate(transform, 0, self.size.height);
  86. transform = CGAffineTransformRotate(transform, -M_PI_2);
  87. break;
  88. case UIImageOrientationUp:
  89. case UIImageOrientationUpMirrored:
  90. break;
  91. }
  92. switch (self.imageOrientation) {
  93. case UIImageOrientationUpMirrored:
  94. case UIImageOrientationDownMirrored:
  95. transform = CGAffineTransformTranslate(transform, self.size.width, 0);
  96. transform = CGAffineTransformScale(transform, -1, 1);
  97. break;
  98. case UIImageOrientationLeftMirrored:
  99. case UIImageOrientationRightMirrored:
  100. transform = CGAffineTransformTranslate(transform, self.size.height, 0);
  101. transform = CGAffineTransformScale(transform, -1, 1);
  102. break;
  103. case UIImageOrientationUp:
  104. case UIImageOrientationDown:
  105. case UIImageOrientationLeft:
  106. case UIImageOrientationRight:
  107. break;
  108. }
  109. // Now we draw the underlying CGImage into a new context, applying the transform
  110. // calculated above.
  111. CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
  112. CGImageGetBitsPerComponent(self.CGImage), 0,
  113. CGImageGetColorSpace(self.CGImage),
  114. CGImageGetBitmapInfo(self.CGImage));
  115. CGContextConcatCTM(ctx, transform);
  116. switch (self.imageOrientation) {
  117. case UIImageOrientationLeft:
  118. case UIImageOrientationLeftMirrored:
  119. case UIImageOrientationRight:
  120. case UIImageOrientationRightMirrored:
  121. // Grr...
  122. CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
  123. break;
  124. default:
  125. CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
  126. break;
  127. }
  128. // And now we just create a new UIImage from the drawing context
  129. CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
  130. UIImage *img = [UIImage imageWithCGImage:cgimg];
  131. CGContextRelease(ctx);
  132. CGImageRelease(cgimg);
  133. return img;
  134. }
  135. //将JPEG格式转换为PNG
  136. -(UIImage *)reduceImage:(UIImage *)image percent:(float)percent
  137. {
  138. NSData *imageData = UIImageJPEGRepresentation(image, percent);
  139. UIImage *newImage = [UIImage imageWithData:imageData];
  140. return newImage;
  141. }
  142. //压缩图片尺寸
  143. - (UIImage *)scaledToSize:(CGSize)newSize
  144. {
  145. //首先要找到缩放比 按长的适配 不足的部分空白
  146. CGFloat rate =newSize.width*1.0/ self.size.width ;
  147. if (self.size.height* rate > newSize.height) {
  148. //过长了。
  149. rate =newSize.height*1.0/ self.size.height ;
  150. }
  151. CGSize size = CGSizeMake(self.size.width*rate, self.size.height*rate);
  152. // Create a graphics image context
  153. UIGraphicsBeginImageContext(size);
  154. // new size
  155. [self drawInRect:CGRectMake(0,0,size.width,size.height)];
  156. // Get the new image from the context
  157. UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  158. // End the context
  159. UIGraphicsEndImageContext();
  160. // Return the new image.
  161. return newImage;
  162. }
  163. - (UIImage *)scaledAndCutToSize:(CGSize)newSize{
  164. //首先要找到缩放比 按短的适配 长的部分裁减掉
  165. CGFloat rate =newSize.width*1.0/ self.size.width ;
  166. if (self.size.height* rate < newSize.height) {
  167. //过长了。
  168. rate =newSize.height*1.0/ self.size.height ;
  169. }
  170. CGSize size = CGSizeMake(self.size.width*rate, self.size.height*rate);
  171. UIGraphicsBeginImageContext(size);
  172. [self drawInRect:CGRectMake(0,0,size.width,size.height)];
  173. // Get the new image from the context
  174. UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  175. // End the context
  176. UIGraphicsEndImageContext();
  177. // Return the new image.
  178. return newImage;
  179. }
  180. - (UIImage*)imageRotatedByDegrees:(CGFloat)degrees
  181. {
  182. CGFloat width = CGImageGetWidth(self.CGImage);
  183. CGFloat height = CGImageGetHeight(self.CGImage);
  184. CGSize rotatedSize;
  185. rotatedSize.width = width;
  186. rotatedSize.height = height;
  187. UIGraphicsBeginImageContext(rotatedSize);
  188. CGContextRef bitmap = UIGraphicsGetCurrentContext();
  189. CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
  190. CGContextRotateCTM(bitmap, degrees * M_PI / 180);
  191. CGContextRotateCTM(bitmap, M_PI);
  192. CGContextScaleCTM(bitmap, -1.0, 1.0);
  193. CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
  194. UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  195. UIGraphicsEndImageContext();
  196. return newImage;
  197. }
  198. + (UIImage *)compressImageWith:(UIImage *)image {
  199. float imageWidth = image.size.width;
  200. float imageHeight = image.size.height;
  201. float width = 640;
  202. float height = image.size.height/(image.size.width/width);
  203. float widthScale = imageWidth /width;
  204. float heightScale = imageHeight /height;
  205. // 创建一个bitmap的context
  206. // 并把它设置成为当前正在使用的context
  207. UIGraphicsBeginImageContext(CGSizeMake(width, height));
  208. if (widthScale > heightScale) {
  209. [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
  210. }
  211. else {
  212. [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
  213. }
  214. // 从当前context中创建一个改变大小后的图片
  215. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  216. // 使当前的context出堆栈
  217. UIGraphicsEndImageContext();
  218. return newImage;
  219. }
  220. /**
  221. 获取网络图片高度
  222. */
  223. + (CGSize)getImageSizeWithURL:(id)URL
  224. {
  225. NSURL * url = nil;
  226. if ([URL isKindOfClass:[NSURL class]]) {
  227. url = URL;
  228. }
  229. if ([URL isKindOfClass:[NSString class]]) {
  230. url = [NSURL URLWithString:URL];
  231. }
  232. if (!URL) {
  233. return CGSizeZero;
  234. }
  235. CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
  236. CGFloat width = 0, height = 0;
  237. if (imageSourceRef) {
  238. // 获取图像属性
  239. CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);
  240. //以下是对手机32位、64位的处理
  241. if (imageProperties != NULL) {
  242. CFNumberRef widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
  243. #if defined(__LP64__) && __LP64__
  244. if (widthNumberRef != NULL) {
  245. CFNumberGetValue(widthNumberRef, kCFNumberFloat64Type, &width);
  246. }
  247. CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
  248. if (heightNumberRef != NULL) {
  249. CFNumberGetValue(heightNumberRef, kCFNumberFloat64Type, &height);
  250. }
  251. #else
  252. if (widthNumberRef != NULL) {
  253. CFNumberGetValue(widthNumberRef, kCFNumberFloat32Type, &width);
  254. }
  255. CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
  256. if (heightNumberRef != NULL) {
  257. CFNumberGetValue(heightNumberRef, kCFNumberFloat32Type, &height);
  258. }
  259. #endif
  260. /***************** 此处解决返回图片宽高相反问题 *****************/
  261. // 图像旋转的方向属性
  262. NSInteger orientation = [(__bridge NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyOrientation) integerValue];
  263. CGFloat temp = 0;
  264. switch (orientation) { // 如果图像的方向不是正的,则宽高互换
  265. case UIImageOrientationLeft: // 向左逆时针旋转90度
  266. case UIImageOrientationRight: // 向右顺时针旋转90度
  267. case UIImageOrientationLeftMirrored: // 在水平翻转之后向左逆时针旋转90度
  268. case UIImageOrientationRightMirrored: { // 在水平翻转之后向右顺时针旋转90度
  269. temp = width;
  270. width = height;
  271. height = temp;
  272. }
  273. break;
  274. default:
  275. break;
  276. }
  277. /***************** 此处解决返回图片宽高相反问题 *****************/
  278. CFRelease(imageProperties);
  279. }
  280. CFRelease(imageSourceRef);
  281. }
  282. return CGSizeMake(width, height);
  283. }
  284. @end