ImageUtil.m 14 KB

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