ImageUtil.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. //
  2. // ImageUtil.m
  3. // kneet2
  4. //
  5. // Created by Jason Lee on 10/15/15.
  6. // Copyright © 2015 ntels. All rights reserved.
  7. //
  8. #import "CommonUtil.h"
  9. #import "ImageUtil.h"
  10. @interface ImageUtil () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
  11. UIImagePickerController *_imagePickerController;
  12. UIAlertController *_alertController;
  13. UIViewController *_presentedViewController;
  14. }
  15. @end
  16. @implementation ImageUtil
  17. #pragma mark - Graphic Util
  18. + (UIImage *)imageWithColor:(UIColor *)color height:(CGFloat)height {
  19. // CGRect appFrame = [UIScreen mainScreen].applicationFrame;
  20. CGFloat y = 0;// appFrame.origin.y > 20 ? 20 : 0;
  21. CGRect rect = CGRectMake(0.0f, y, 1.0f, height);
  22. UIGraphicsBeginImageContext(rect.size);
  23. CGContextRef context = UIGraphicsGetCurrentContext();
  24. CGContextSetFillColorWithColor(context, [color CGColor]);
  25. CGContextFillRect(context, rect);
  26. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  27. UIGraphicsEndImageContext();
  28. return image;
  29. }
  30. + (CGFloat)getImageAspectRatio:(UIImage *)image {
  31. return image.size.width / image.size.height;
  32. }
  33. //해당 이미지를 주어진 크키에 맞추어 리사이즈하여 반환함.
  34. //resize image
  35. + (UIImage *)resizeImage:(UIImage *)image width:(float)resizeWidth height:(float)resizeHeight {
  36. UIGraphicsBeginImageContext(CGSizeMake(resizeWidth, resizeHeight));
  37. CGContextRef context = UIGraphicsGetCurrentContext();
  38. CGContextTranslateCTM(context, 0.0, resizeHeight);
  39. CGContextScaleCTM(context, 1.0, -1.0);
  40. CGContextDrawImage(context, CGRectMake(0.0, 0.0, resizeWidth, resizeHeight), [image CGImage]);
  41. UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  42. UIGraphicsEndImageContext();
  43. return scaledImage;
  44. }
  45. //
  46. //- (UIImage *)resizedImage:(CGSize)size imageOrientation:(UIImageOrientation)imageOrientation {
  47. // CGSize imageSize = self.size;
  48. // CGFloat horizontalRatio = size.width / imageSize.width;
  49. // CGFloat verticalRatio = size.height / imageSize.height;
  50. // CGFloat ratio = MIN(horizontalRatio, verticalRatio);
  51. // CGSize targetSize = CGSizeMake(imageSize.width * ratio, imageSize.height * ratio);
  52. //
  53. // UIGraphicsBeginImageContextWithOptions(size, YES, 1.0f);
  54. // CGContextRef context = UIGraphicsGetCurrentContext();
  55. //
  56. // CGContextScaleCTM(context, 1.0f, -1.0f);
  57. // CGContextTranslateCTM(context, 0.0f, -size.height);
  58. //
  59. // CGAffineTransform transform = CGAffineTransformIdentity;
  60. // if (imageOrientation == UIImageOrientationRight || imageOrientation == UIImageOrientationRightMirrored) {
  61. // transform = CGAffineTransformTranslate(transform, 0.0f, size.height);
  62. // transform = CGAffineTransformRotate(transform, -M_PI_2);
  63. // } else if (imageOrientation == UIImageOrientationLeft || imageOrientation == UIImageOrientationLeftMirrored) {
  64. // transform = CGAffineTransformTranslate(transform, size.width, 0.0f);
  65. // transform = CGAffineTransformRotate(transform, M_PI_2);
  66. // } else if (imageOrientation == UIImageOrientationDown || imageOrientation == UIImageOrientationDownMirrored) {
  67. // transform = CGAffineTransformTranslate(transform, size.width, size.height);
  68. // transform = CGAffineTransformRotate(transform, M_PI);
  69. // }
  70. // CGContextConcatCTM(context, transform);
  71. //
  72. // CGContextDrawImage(context, CGRectMake((size.width - targetSize.width) / 2, (size.height - targetSize.height) / 2, targetSize.width, targetSize.height), self.CGImage);
  73. //
  74. // UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
  75. // UIGraphicsEndImageContext();
  76. //
  77. // return resizedImage;
  78. //}
  79. + (UIImage *)resizeImage:(UIImage *)image width:(float)resizeWidth {
  80. float ratio = [ImageUtil getImageAspectRatio:image];
  81. float resizeHeight = resizeWidth / ratio;
  82. return [ImageUtil resizeImage:image size:CGSizeMake(resizeWidth, resizeHeight) imageOrientation:image.imageOrientation];
  83. }
  84. + (UIImage *)resizeImage:(UIImage *)image height:(float)resizeHeight {
  85. float ratio = [ImageUtil getImageAspectRatio:image];
  86. float resizeWidth = resizeHeight * ratio;
  87. return [ImageUtil resizeImage:image width:resizeWidth height:resizeHeight];
  88. }
  89. + (CGRect)convertCropRect:(CGRect)cropRect image:(UIImage *)image {
  90. UIImage *originalImage = image;
  91. CGSize size = originalImage.size;
  92. CGFloat x = cropRect.origin.x;
  93. CGFloat y = cropRect.origin.y;
  94. CGFloat width = cropRect.size.width;
  95. CGFloat height = cropRect.size.height;
  96. UIImageOrientation imageOrientation = originalImage.imageOrientation;
  97. if (imageOrientation == UIImageOrientationRight || imageOrientation == UIImageOrientationRightMirrored) {
  98. cropRect.origin.x = y;
  99. cropRect.origin.y = size.width - cropRect.size.width - x;
  100. cropRect.size.width = height;
  101. cropRect.size.height = width;
  102. } else if (imageOrientation == UIImageOrientationLeft || imageOrientation == UIImageOrientationLeftMirrored) {
  103. cropRect.origin.x = size.height - cropRect.size.height - y;
  104. cropRect.origin.y = x;
  105. cropRect.size.width = height;
  106. cropRect.size.height = width;
  107. } else if (imageOrientation == UIImageOrientationDown || imageOrientation == UIImageOrientationDownMirrored) {
  108. cropRect.origin.x = size.width - cropRect.size.width - x;
  109. cropRect.origin.y = size.height - cropRect.size.height - y;
  110. }
  111. return cropRect;
  112. }
  113. + (UIImage *)croppedImage:(CGRect)cropRect image:(UIImage *)image {
  114. CGImageRef croppedCGImage = CGImageCreateWithImageInRect(image.CGImage ,cropRect);
  115. UIImage *croppedImage = [UIImage imageWithCGImage:croppedCGImage scale:1.0f orientation:image.imageOrientation];
  116. CGImageRelease(croppedCGImage);
  117. return croppedImage;
  118. }
  119. + (UIImage *)resizeImage:(UIImage *)image size:(CGSize)size imageOrientation:(UIImageOrientation)imageOrientation {
  120. if (size.width > image.size.width) {
  121. size.width = image.size.width;
  122. }
  123. if (size.height > image.size.height) {
  124. size.height = image.size.height;
  125. }
  126. CGSize imageSize = image.size;
  127. CGFloat horizontalRatio = size.width / imageSize.width;
  128. CGFloat verticalRatio = size.height / imageSize.height;
  129. CGFloat ratio = MIN(horizontalRatio, verticalRatio);
  130. CGSize targetSize = CGSizeMake(imageSize.width * ratio, imageSize.height * ratio);
  131. UIGraphicsBeginImageContextWithOptions(size, YES, 1.0f);
  132. CGContextRef context = UIGraphicsGetCurrentContext();
  133. CGContextScaleCTM(context, 1.0f, -1.0f);
  134. CGContextTranslateCTM(context, 0.0f, -size.height);
  135. CGAffineTransform transform = CGAffineTransformIdentity;
  136. if (imageOrientation == UIImageOrientationRight || imageOrientation == UIImageOrientationRightMirrored) {
  137. transform = CGAffineTransformTranslate(transform, 0.0f, size.height);
  138. transform = CGAffineTransformRotate(transform, -M_PI_2);
  139. } else if (imageOrientation == UIImageOrientationLeft || imageOrientation == UIImageOrientationLeftMirrored) {
  140. transform = CGAffineTransformTranslate(transform, size.width, 0.0f);
  141. transform = CGAffineTransformRotate(transform, M_PI_2);
  142. } else if (imageOrientation == UIImageOrientationDown || imageOrientation == UIImageOrientationDownMirrored) {
  143. transform = CGAffineTransformTranslate(transform, size.width, size.height);
  144. transform = CGAffineTransformRotate(transform, M_PI);
  145. }
  146. CGContextConcatCTM(context, transform);
  147. CGContextDrawImage(context, CGRectMake((size.width - targetSize.width) / 2, (size.height - targetSize.height) / 2, targetSize.width, targetSize.height), image.CGImage);
  148. UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
  149. UIGraphicsEndImageContext();
  150. return resizedImage;
  151. }
  152. + (UIImage*)getMaskedImageWithSourchImage:(UIImage *)srcImage andMaskImage:(UIImage *)maskImage {
  153. CGImageRef maskRef = maskImage.CGImage;
  154. CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
  155. CGImageGetHeight(maskRef),
  156. CGImageGetBitsPerComponent(maskRef),
  157. CGImageGetBitsPerPixel(maskRef),
  158. CGImageGetBytesPerRow(maskRef),
  159. CGImageGetDataProvider(maskRef), NULL, false);
  160. CGImageRef masked = CGImageCreateWithMask([srcImage CGImage], mask);
  161. CGImageRelease(mask);
  162. UIImage *imageMask = [UIImage imageWithCGImage:masked];
  163. CGImageRelease(masked);
  164. return imageMask;
  165. }
  166. + (UIImage *)imageToGrayScale:(UIImage *)image {
  167. if (!image)
  168. return nil;
  169. int kRed = 1;
  170. int kGreen = 2;
  171. int kBlue = 4;
  172. int colors = kGreen | kBlue | kRed;
  173. int m_width = image.size.width;
  174. int m_height = image.size.height;
  175. uint32_t *rgbImage = (uint32_t *) malloc(m_width * m_height * sizeof(uint32_t));
  176. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  177. CGContextRef context = CGBitmapContextCreate(rgbImage, m_width, m_height, 8, m_width * 4, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  178. CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
  179. CGContextSetShouldAntialias(context, NO);
  180. CGContextDrawImage(context, CGRectMake(0, 0, m_width, m_height), [image CGImage]);
  181. CGContextRelease(context);
  182. CGColorSpaceRelease(colorSpace);
  183. // now convert to grayscale
  184. uint8_t *m_imageData = (uint8_t *) malloc(m_width * m_height);
  185. for(int y = 0; y < m_height; y++) {
  186. for(int x = 0; x < m_width; x++) {
  187. uint32_t rgbPixel=rgbImage[y*m_width+x];
  188. uint32_t sum=0,count=0;
  189. if (colors & kRed) {sum += (rgbPixel>>24)&255; count++;}
  190. if (colors & kGreen) {sum += (rgbPixel>>16)&255; count++;}
  191. if (colors & kBlue) {sum += (rgbPixel>>8)&255; count++;}
  192. m_imageData[y*m_width+x]=sum/count;
  193. }
  194. }
  195. free(rgbImage);
  196. // convert from a gray scale image back into a UIImage
  197. uint8_t *result = (uint8_t *) calloc(m_width * m_height *sizeof(uint32_t), 1);
  198. // process the image back to rgb
  199. for(int i = 0; i < m_height * m_width; i++) {
  200. result[i*4]=0;
  201. int val=m_imageData[i];
  202. result[i*4+1]=val;
  203. result[i*4+2]=val;
  204. result[i*4+3]=val;
  205. }
  206. // create a UIImage
  207. colorSpace = CGColorSpaceCreateDeviceRGB();
  208. context = CGBitmapContextCreate(result, m_width, m_height, 8, m_width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  209. CGImageRef destImage = CGBitmapContextCreateImage(context);
  210. CGContextRelease(context);
  211. CGColorSpaceRelease(colorSpace);
  212. UIImage *resultUIImage = [UIImage imageWithCGImage:destImage];
  213. CGImageRelease(destImage);
  214. free(m_imageData);
  215. // make sure the data will be released by giving it to an autoreleased NSData
  216. [NSData dataWithBytesNoCopy:result length:m_width * m_height];
  217. return resultUIImage;
  218. }
  219. //이미지사이즈를 늘림 - 나인패치
  220. #pragma resizableImageWithCapInsets
  221. + (UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)make resizingMode:(UIImageResizingMode)resizingMode img:(UIImage *)img{
  222. UIImage *image = nil;
  223. if (IOS_VERSION < 6.0f) {
  224. image = [img resizableImageWithCapInsets:make];
  225. } else {
  226. image = [img resizableImageWithCapInsets:make resizingMode:resizingMode];
  227. }
  228. return image;
  229. }
  230. + (UIImage *)stretchedImage:(UIImage *)srcImage expectSize:(CGSize)size {
  231. int st_width = size.width > srcImage.size.width ? (size.width - srcImage.size.width) / 2 : 0;
  232. int st_height = size.height > srcImage.size.height ? (size.height - srcImage.size.height) / 2 : 0;
  233. CGFloat capWidth = (st_width / 2);
  234. CGFloat capHeight = (st_height / 2);
  235. if (capWidth > 0) {
  236. capWidth = capWidth >= srcImage.size.width ? srcImage.size.width / 2 : capWidth;
  237. }
  238. if (capHeight > 0) {
  239. capHeight = capHeight >= srcImage.size.width ? srcImage.size.width / 2 : capHeight;
  240. }
  241. return [ImageUtil resizableImageWithCapInsets:UIEdgeInsetsMake(capHeight, capWidth, capHeight, capWidth) resizingMode:UIImageResizingModeStretch img:srcImage];
  242. }
  243. #pragma mark - Upload Util
  244. - (void)prepareImagePicker:(UIViewController *)vc {
  245. _presentedViewController = vc;
  246. _alertController = [UIAlertController
  247. alertControllerWithTitle:NSLocalizedString(@"사진 선택", @"사진 선택")
  248. message:nil
  249. preferredStyle:UIAlertControllerStyleActionSheet];
  250. UIAlertAction* album = [UIAlertAction actionWithTitle:NSLocalizedString(@"사진앨범", @"사진앨범") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  251. [_alertController dismissViewControllerAnimated:YES completion:nil];
  252. [self showImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
  253. }];
  254. UIAlertAction* camera = [UIAlertAction actionWithTitle:NSLocalizedString(@"카메라", @"카메라") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  255. [_alertController dismissViewControllerAnimated:YES completion:nil];
  256. [self showImagePickerController:UIImagePickerControllerSourceTypeCamera];
  257. }];
  258. UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"취소", @"취소") style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  259. [_alertController dismissViewControllerAnimated:YES completion:nil];
  260. }];
  261. [_alertController addAction:album];
  262. [_alertController addAction:camera];
  263. [_alertController addAction:cancel];
  264. [_presentedViewController presentViewController:_alertController animated:YES completion:nil];
  265. }
  266. #pragma mark - 카메라/포토앨범 표시
  267. - (void)showImagePickerController:(UIImagePickerControllerSourceType)sourceType
  268. {
  269. _imagePickerController = [[UIImagePickerController alloc] init];
  270. _imagePickerController.delegate = self;
  271. UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  272. btnCancel.frame = CGRectMake(0, 0, 50, 30);
  273. [btnCancel setTitle:@"취소" forState:UIControlStateNormal];
  274. [btnCancel addTarget:self action:@selector(btnCancelTouched:) forControlEvents:UIControlEventTouchUpInside];
  275. _imagePickerController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnCancel];
  276. if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
  277. _imagePickerController.allowsEditing = YES;
  278. _imagePickerController.sourceType = sourceType;
  279. _imagePickerController.navigationBar.tintColor = RGBCOLOR(46, 141, 205); //Cancel button text color
  280. _imagePickerController.navigationBar.translucent = NO;
  281. [_presentedViewController presentViewController:_imagePickerController animated:YES completion:nil];
  282. }
  283. }
  284. - (void)btnCancelTouched:(id)sender {
  285. [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
  286. }
  287. - (UIStatusBarStyle)preferredStatusBarStyle {
  288. return UIStatusBarStyleLightContent;
  289. }
  290. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  291. CGRect cropRect = [[info valueForKey:UIImagePickerControllerCropRect] CGRectValue];
  292. //NSLog(@"cropRect: %@", NSStringFromCGRect(cropRect));
  293. UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
  294. cropRect = [ImageUtil convertCropRect:cropRect image:image]; //orientaion change
  295. image = [ImageUtil croppedImage:cropRect image:image];
  296. image = [ImageUtil resizeImage:image width:100.0f];
  297. [_presentedViewController dismissViewControllerAnimated:YES completion:^{
  298. if ([self.delegate respondsToSelector:@selector(didFinishPickingImage:)]) {
  299. [self.delegate didFinishPickingImage:image];
  300. }
  301. }];
  302. }
  303. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  304. // UIViewController *vc = [CommonUtil currentViewController];
  305. [_presentedViewController dismissViewControllerAnimated:YES completion:nil];
  306. }
  307. @end