DKCameraViewController.m 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. //
  2. // BQCamera.m
  3. // BQCommunity
  4. //
  5. //
  6. #import <AVFoundation/AVFoundation.h>
  7. #import <ImageIO/ImageIO.h>
  8. #import <objc/message.h>
  9. #import "DKCameraViewController.h"
  10. #import "DKCameraImageView.h"
  11. #import "DKCameraView.h"
  12. #import "DKPhoto.h"
  13. static CGFloat ZLCameraColletionViewW = 80;
  14. static CGFloat ZLCameraColletionViewPadding = 20;
  15. static CGFloat BOTTOM_HEIGHT = 60;
  16. @interface DKCameraViewController () <UIActionSheetDelegate,UICollectionViewDataSource,UICollectionViewDelegate,AVCaptureMetadataOutputObjectsDelegate,DKCameraImageViewDelegate,DKCameraViewDelegate,DKPhotoPickerViewControllerDelegate,DKPhotoPickerBrowserViewControllerDataSource,DKPhotoPickerBrowserViewControllerDelegate>
  17. @property (weak,nonatomic) DKCameraView *caramView;
  18. @property (strong, nonatomic) UICollectionView *collectionView;
  19. @property (strong, nonatomic) UIViewController *currentViewController;
  20. // Datas
  21. @property (strong, nonatomic) NSMutableArray *images;
  22. @property (strong, nonatomic) NSMutableDictionary *dictM;
  23. // 完成后回调
  24. @property (copy, nonatomic) DKComplate complate;
  25. // AVFoundation
  26. @property (strong, nonatomic) AVCaptureSession *session;
  27. @property (strong, nonatomic) AVCaptureStillImageOutput *captureOutput;
  28. @property (strong, nonatomic) AVCaptureDevice *device;
  29. @property (strong,nonatomic)AVCaptureDeviceInput * input;
  30. @property (strong,nonatomic)AVCaptureMetadataOutput * output;
  31. @property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
  32. @end
  33. @implementation DKCameraViewController
  34. #pragma mark - Getter
  35. #pragma mark Data
  36. - (NSMutableArray *)images{
  37. if (!_images) {
  38. _images = [NSMutableArray array];
  39. }
  40. return _images;
  41. }
  42. - (NSMutableDictionary *)dictM{
  43. if (!_dictM) {
  44. _dictM = [NSMutableDictionary dictionary];
  45. }
  46. return _dictM;
  47. }
  48. #pragma mark View
  49. - (UICollectionView *)collectionView{
  50. if (!_collectionView) {
  51. UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
  52. layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
  53. layout.itemSize = CGSizeMake(ZLCameraColletionViewW, ZLCameraColletionViewW);
  54. layout.minimumLineSpacing = ZLCameraColletionViewPadding;
  55. CGFloat collectionViewH = ZLCameraColletionViewW;
  56. CGFloat collectionViewY = self.caramView.height - collectionViewH - 10;
  57. UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(ZLCameraColletionViewPadding, collectionViewY, self.view.width, collectionViewH)
  58. collectionViewLayout:layout];
  59. collectionView.backgroundColor = [UIColor clearColor];
  60. [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
  61. collectionView.delegate = self;
  62. collectionView.dataSource = self;
  63. [self.caramView addSubview:collectionView];
  64. self.collectionView = collectionView;
  65. }
  66. return _collectionView;
  67. }
  68. - (void) initialize
  69. {
  70. //1.创建会话层
  71. self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  72. // Input
  73. self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
  74. // Output
  75. self.captureOutput = [[AVCaptureStillImageOutput alloc] init];
  76. NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
  77. [self.captureOutput setOutputSettings:outputSettings];
  78. // Session
  79. self.session = [[AVCaptureSession alloc]init];
  80. [self.session setSessionPreset:AVCaptureSessionPresetHigh];
  81. if ([self.session canAddInput:self.input])
  82. {
  83. [self.session addInput:self.input];
  84. }
  85. if ([self.session canAddOutput:_captureOutput])
  86. {
  87. [self.session addOutput:_captureOutput];
  88. }
  89. self.preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
  90. self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
  91. self.preview.frame = self.view.bounds;
  92. DKCameraView *caramView = [[DKCameraView alloc] initWithFrame:CGRectMake(0, 40, self.view.width, self.view.height - 40 - BOTTOM_HEIGHT)];
  93. caramView.backgroundColor = [UIColor clearColor];
  94. caramView.delegate = self;
  95. [self.view addSubview:caramView];
  96. [self.view.layer insertSublayer:self.preview atIndex:0];
  97. self.caramView = caramView;
  98. }
  99. - (void)cameraDidSelected:(DKCameraView *)camera{
  100. [self.device lockForConfiguration:nil];
  101. [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
  102. [self.device setFocusPointOfInterest:CGPointMake(50,50)];
  103. //操作完成后,记得进行unlock。
  104. [self.device unlockForConfiguration];
  105. }
  106. //对焦回调
  107. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  108. if( [keyPath isEqualToString:@"adjustingFocus"] ){}
  109. }
  110. - (void)viewDidLoad{
  111. [super viewDidLoad];
  112. [self initialize];
  113. [self setup];
  114. if (self.session) {
  115. [self.session startRunning];
  116. }
  117. }
  118. #pragma mark 初始化按钮
  119. - (UIButton *) setupButtonWithImageName : (NSString *) imageName andX : (CGFloat ) x{
  120. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  121. [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
  122. button.backgroundColor = [UIColor clearColor];
  123. button.width = 50;
  124. button.y = 0;
  125. button.height = self.topView.height;
  126. button.x = x;
  127. [self.view addSubview:button];
  128. return button;
  129. }
  130. #pragma mark -初始化界面
  131. - (void) setup{
  132. //[UIApplication sharedApplication].statusBarHidden = YES;
  133. CGFloat width = 50;
  134. CGFloat margin = 20;
  135. UIView *topView = [[UIView alloc] init];
  136. topView.backgroundColor = [UIColor blackColor];
  137. topView.frame = CGRectMake(0, 0, self.view.width, 40);
  138. [self.view addSubview:topView];
  139. self.topView = topView;
  140. // 头部View
  141. UIButton *deviceBtn = [self setupButtonWithImageName:@"xiang" andX:self.view.width - margin - width];
  142. [deviceBtn addTarget:self action:@selector(changeCameraDevice:) forControlEvents:UIControlEventTouchUpInside];
  143. UIButton *flashBtn = [self setupButtonWithImageName:@"shanguangdeng" andX:10];
  144. [flashBtn addTarget:self action:@selector(flashCameraDevice:) forControlEvents:UIControlEventTouchUpInside];
  145. UIButton *closeBtn = [self setupButtonWithImageName:@"shanguangdeng2" andX:60];
  146. [closeBtn addTarget:self action:@selector(closeFlashlight:) forControlEvents:UIControlEventTouchUpInside];
  147. // 底部View
  148. UIView *controlView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height-BOTTOM_HEIGHT, self.view.width, BOTTOM_HEIGHT)];
  149. controlView.backgroundColor = [UIColor clearColor];
  150. controlView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
  151. self.controlView = controlView;
  152. UIView *contentView = [[UIView alloc] init];
  153. contentView.frame = controlView.bounds;
  154. contentView.backgroundColor = [UIColor blackColor];
  155. contentView.alpha = 0.3;
  156. [controlView addSubview:contentView];
  157. CGFloat x = (self.view.width - width) / 3;
  158. //取消
  159. UIButton *cancalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  160. cancalBtn.frame = CGRectMake(margin, 0, x, controlView.height);
  161. [cancalBtn setTitle:@"取消" forState:UIControlStateNormal];
  162. [cancalBtn addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
  163. [controlView addSubview:cancalBtn];
  164. //拍照
  165. UIButton *cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  166. cameraBtn.frame = CGRectMake(x+margin, margin / 4, x, controlView.height - margin / 2);
  167. cameraBtn.showsTouchWhenHighlighted = YES;
  168. cameraBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
  169. [cameraBtn setImage:[UIImage imageNamed:@"paizhao"] forState:UIControlStateNormal];
  170. [cameraBtn addTarget:self action:@selector(stillImage:) forControlEvents:UIControlEventTouchUpInside];
  171. [controlView addSubview:cameraBtn];
  172. // 完成
  173. UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  174. doneBtn.frame = CGRectMake(self.view.width - 2 * margin - width, 0, width, controlView.height);
  175. [doneBtn setTitle:@"完成" forState:UIControlStateNormal];
  176. [doneBtn addTarget:self action:@selector(doneAction) forControlEvents:UIControlEventTouchUpInside];
  177. [controlView addSubview:doneBtn];
  178. [self.view addSubview:controlView];
  179. }
  180. - (NSInteger ) numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
  181. return 1;
  182. }
  183. - (NSInteger ) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  184. return self.images.count;
  185. }
  186. - (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
  187. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  188. DKCamera *camera = self.images[indexPath.item];
  189. DKCameraImageView *lastView = [cell.contentView.subviews lastObject];
  190. if(![lastView isKindOfClass:[DKCameraImageView class]]){
  191. // 解决重用问题
  192. UIImage *image = camera.thumbImage;
  193. DKCameraImageView *imageView = [[DKCameraImageView alloc] init];
  194. imageView.delegatge = self;
  195. imageView.edit = YES;
  196. imageView.image = image;
  197. imageView.frame = cell.bounds;
  198. imageView.contentMode = UIViewContentModeScaleAspectFill;
  199. [cell.contentView addSubview:imageView];
  200. }
  201. lastView.image = camera.thumbImage;
  202. return cell;
  203. }
  204. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  205. DKPhotoPickerBrowserViewController *browserVc = [[DKPhotoPickerBrowserViewController alloc] init];
  206. browserVc.toView = [[[[collectionView cellForItemAtIndexPath:indexPath] contentView] subviews] lastObject];
  207. browserVc.dataSource = self;
  208. browserVc.delegate = self;
  209. browserVc.currentIndexPath = [NSIndexPath indexPathForItem:indexPath.item inSection:0];
  210. browserVc.editing = YES;
  211. [self presentViewController:browserVc animated:NO completion:nil];
  212. }
  213. #pragma mark - <ZLPhotoPickerBrowserViewControllerDataSource>
  214. - (NSInteger)photoBrowser:(DKPhotoPickerBrowserViewController *)photoBrowser numberOfItemsInSection:(NSUInteger)section{
  215. return self.images.count;
  216. }
  217. - (DKPhotoPickerBrowserPhoto *) photoBrowser:(DKPhotoPickerBrowserViewController *)pickerBrowser photoAtIndexPath:(NSIndexPath *)indexPath{
  218. id imageObj = [[self.images objectAtIndex:indexPath.row] fullScreenImage];
  219. DKPhotoPickerBrowserPhoto *photo = [DKPhotoPickerBrowserPhoto photoAnyImageObjWith:imageObj];
  220. UICollectionViewCell *cell = (UICollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
  221. UIImageView *imageView = [[cell.contentView subviews] lastObject];
  222. photo.thumbImage = imageView.image;
  223. return photo;
  224. }
  225. - (void)deleteImageView:(DKCameraImageView *)imageView{
  226. NSMutableArray *arrM = [self.images mutableCopy];
  227. for (DKCamera *camera in self.images) {
  228. UIImage *image = camera.thumbImage;
  229. if ([image isEqual:imageView.image]) {
  230. [arrM removeObject:camera];
  231. }
  232. }
  233. self.images = arrM;
  234. [self.collectionView reloadData];
  235. }
  236. - (void)startCameraOrPhotoFileWithViewController:(UIViewController *)viewController complate:(DKComplate)complate{
  237. self.currentViewController = viewController;
  238. // UIActionSheet *myActionSheet = [[UIActionSheet alloc]initWithTitle:nil
  239. // delegate:self
  240. // cancelButtonTitle:@"取消"
  241. // destructiveButtonTitle:nil
  242. // otherButtonTitles:@"打开照相机",@"从手机相册获取",nil];
  243. //
  244. // [myActionSheet showInView:[UIApplication sharedApplication].keyWindow];
  245. self.complate = complate;
  246. [self takePhoto];
  247. }
  248. #pragma mark - ActionSheet Delegate
  249. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
  250. {
  251. switch (buttonIndex)
  252. {
  253. case 0: //打开照相机拍照
  254. [self takePhoto];
  255. break;
  256. case 1: //打开本地相册
  257. [self LocalPhoto];
  258. break;
  259. }
  260. }
  261. -(void)Captureimage
  262. {
  263. //get connection
  264. AVCaptureConnection *videoConnection = nil;
  265. for (AVCaptureConnection *connection in self.captureOutput.connections) {
  266. for (AVCaptureInputPort *port in [connection inputPorts]) {
  267. if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
  268. videoConnection = connection;
  269. break;
  270. }
  271. }
  272. if (videoConnection) { break; }
  273. }
  274. //get UIImage
  275. [self.captureOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:
  276. ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
  277. CFDictionaryRef exifAttachments =
  278. CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
  279. if (exifAttachments) {
  280. // Do something with the attachments.
  281. }
  282. // Continue as appropriate.
  283. NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
  284. UIImage *t_image = [UIImage imageWithData:imageData];
  285. NSDateFormatter *formater = [[NSDateFormatter alloc] init];
  286. formater.dateFormat = @"yyyyMMddHHmmss";
  287. NSString *currentTimeStr = [[formater stringFromDate:[NSDate date]] stringByAppendingFormat:@"_%d.jpg" ,arc4random_uniform(10000)];
  288. t_image = [self fixOrientation:t_image];
  289. NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:currentTimeStr];
  290. [UIImagePNGRepresentation(t_image) writeToFile:path atomically:YES];
  291. NSData *data = UIImageJPEGRepresentation(t_image, 0.3);
  292. DKCamera *camera = [[DKCamera alloc] init];
  293. camera.imagePath = path;
  294. camera.thumbImage = [UIImage imageWithData:data];
  295. [self.images addObject:camera];
  296. [self.collectionView reloadData];
  297. [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:self.images.count - 1 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionRight];
  298. }];
  299. }
  300. -(void)CaptureStillImage
  301. {
  302. [self Captureimage];
  303. }
  304. //开始拍照
  305. -(void)takePhoto
  306. {
  307. if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
  308. {
  309. DKCameraViewController *camreaVc = [[DKCameraViewController alloc] init];
  310. camreaVc.complate = self.complate;
  311. [[[[UIApplication sharedApplication].windows firstObject] rootViewController] presentViewController:camreaVc animated:YES completion:nil];
  312. }else
  313. {
  314. NSLog(@"模拟其中无法打开照相机,请在真机中使用");
  315. }
  316. }
  317. - (void)photoBrowser:(DKPhotoPickerBrowserViewController *)photoBrowser removePhotoAtIndexPath:(NSIndexPath *)indexPath{
  318. if (indexPath.row > [self.images count]) return;
  319. [self.images removeObjectAtIndex:indexPath.row];
  320. [self.collectionView reloadData];
  321. }
  322. //打开本地相册
  323. -(void)LocalPhoto
  324. {
  325. DKPhotoPickerViewController *pickerVc = [[DKPhotoPickerViewController alloc] init];
  326. // 最多能选9张图片
  327. pickerVc.minCount = 9;
  328. pickerVc.status = PickerViewShowStatusCameraRoll;
  329. pickerVc.delegate = self;
  330. [pickerVc show];
  331. }
  332. - (void)pickerViewControllerDoneAsstes:(NSArray *)assets{
  333. if (self.complate) {
  334. self.complate(assets);
  335. }
  336. if ([self.currentViewController respondsToSelector:@selector(pickerViewControllerDoneAsstes:)]) {
  337. [self.currentViewController performSelectorInBackground:@selector(pickerViewControllerDoneAsstes:) withObject:assets];
  338. }
  339. }
  340. - (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
  341. {
  342. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  343. for ( AVCaptureDevice *device in devices )
  344. if ( device.position == position )
  345. return device;
  346. return nil;
  347. }
  348. - (void)changeCameraDevice:(id)sender
  349. {
  350. // 翻转
  351. [UIView beginAnimations:@"animation" context:nil];
  352. [UIView setAnimationDuration:.5f];
  353. [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
  354. [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
  355. [UIView commitAnimations];
  356. NSArray *inputs = self.session.inputs;
  357. for ( AVCaptureDeviceInput *input in inputs ) {
  358. AVCaptureDevice *device = input.device;
  359. if ( [device hasMediaType:AVMediaTypeVideo] ) {
  360. AVCaptureDevicePosition position = device.position;
  361. AVCaptureDevice *newCamera = nil;
  362. AVCaptureDeviceInput *newInput = nil;
  363. if (position == AVCaptureDevicePositionFront)
  364. newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
  365. else
  366. newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
  367. newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
  368. [self.session beginConfiguration];
  369. [self.session removeInput:input];
  370. [self.session addInput:newInput];
  371. // Changes take effect once the outermost commitConfiguration is invoked.
  372. [self.session commitConfiguration];
  373. break;
  374. }
  375. }
  376. }
  377. - (void) flashLightModel : (codeBlock) codeBlock{
  378. if (!codeBlock) return;
  379. [self.session beginConfiguration];
  380. [self.device lockForConfiguration:nil];
  381. codeBlock();
  382. [self.device unlockForConfiguration];
  383. [self.session commitConfiguration];
  384. [self.session startRunning];
  385. }
  386. - (void) flashCameraDevice:(UIButton *)sender{
  387. [self flashLightModel:^{
  388. [self.device setTorchMode:AVCaptureTorchModeOn];
  389. }];
  390. }
  391. - (void) closeFlashlight:(UIButton *)sender{
  392. // self.device.torchMode == AVCaptureTorchModeOff 判断
  393. [self flashLightModel:^{
  394. [self.device setTorchMode:AVCaptureTorchModeOff];
  395. }];
  396. }
  397. - (void)cancel:(id)sender
  398. {
  399. [self dismissViewControllerAnimated:YES completion:nil];
  400. }
  401. //完成、取消
  402. - (void)doneAction
  403. {
  404. //关闭相册界面
  405. if(self.complate){
  406. self.complate(self.images);
  407. }
  408. [self cancel:nil];
  409. }
  410. //拍照
  411. - (void)stillImage:(id)sender
  412. {
  413. [self Captureimage];
  414. UIView *maskView = [[UIView alloc] init];
  415. maskView.frame = self.view.bounds;
  416. maskView.backgroundColor = [UIColor whiteColor];
  417. [self.view addSubview:maskView];
  418. [UIView animateWithDuration:.5 animations:^{
  419. maskView.alpha = 0;
  420. } completion:^(BOOL finished) {
  421. [maskView removeFromSuperview];
  422. }];
  423. }
  424. - (BOOL)shouldAutorotate{
  425. return YES;
  426. }
  427. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
  428. return YES;
  429. }
  430. - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
  431. return UIInterfaceOrientationPortrait;
  432. }
  433. - (UIImage *)fixOrientation:(UIImage *)srcImg
  434. {
  435. if (srcImg.imageOrientation == UIImageOrientationUp) return srcImg;
  436. CGAffineTransform transform = CGAffineTransformIdentity;
  437. switch (srcImg.imageOrientation) {
  438. case UIImageOrientationDown:
  439. case UIImageOrientationDownMirrored:
  440. transform = CGAffineTransformTranslate(transform, srcImg.size.width, srcImg.size.height);
  441. transform = CGAffineTransformRotate(transform, M_PI);
  442. break;
  443. case UIImageOrientationLeft:
  444. case UIImageOrientationLeftMirrored:
  445. transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
  446. transform = CGAffineTransformRotate(transform, M_PI_2);
  447. break;
  448. case UIImageOrientationRight:
  449. case UIImageOrientationRightMirrored:
  450. transform = CGAffineTransformTranslate(transform, 0, srcImg.size.height);
  451. transform = CGAffineTransformRotate(transform, -M_PI_2);
  452. break;
  453. case UIImageOrientationUp:
  454. case UIImageOrientationUpMirrored:
  455. break;
  456. }
  457. switch (srcImg.imageOrientation) {
  458. case UIImageOrientationUpMirrored:
  459. case UIImageOrientationDownMirrored:
  460. transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
  461. transform = CGAffineTransformScale(transform, -1, 1);
  462. break;
  463. case UIImageOrientationLeftMirrored:
  464. case UIImageOrientationRightMirrored:
  465. transform = CGAffineTransformTranslate(transform, srcImg.size.height, 0);
  466. transform = CGAffineTransformScale(transform, -1, 1);
  467. break;
  468. case UIImageOrientationUp:
  469. case UIImageOrientationDown:
  470. case UIImageOrientationLeft:
  471. case UIImageOrientationRight:
  472. break;
  473. }
  474. CGContextRef ctx = CGBitmapContextCreate(NULL, srcImg.size.width, srcImg.size.height,
  475. CGImageGetBitsPerComponent(srcImg.CGImage), 0,
  476. CGImageGetColorSpace(srcImg.CGImage),
  477. CGImageGetBitmapInfo(srcImg.CGImage));
  478. CGContextConcatCTM(ctx, transform);
  479. switch (srcImg.imageOrientation) {
  480. case UIImageOrientationLeft:
  481. case UIImageOrientationLeftMirrored:
  482. case UIImageOrientationRight:
  483. case UIImageOrientationRightMirrored:
  484. CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.height,srcImg.size.width), srcImg.CGImage);
  485. break;
  486. default:
  487. CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.width,srcImg.size.height), srcImg.CGImage);
  488. break;
  489. }
  490. CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
  491. UIImage *img = [UIImage imageWithCGImage:cgimg];
  492. CGContextRelease(ctx);
  493. CGImageRelease(cgimg);
  494. return img;
  495. }
  496. @end