IOS study note 39-take a photo, select a picture from the album, and crop the image

Source: Internet
Author: User

Article 1: Happy New Year! Thanks to my colleagues who have been paying attention to my blog. With your support, I have the motivation to become better and better! I haven't written a blog for a while, because I was very busy a while ago and had no time to sort it out. Today I mainly implement a small demo. We know that on Instagram or path, the pictures are square pictures, the source image must be captured when you get this kind of profile picture. Today, I took the time to sort it out and record it as follows! I wrote an article titled IOS study notes 22-File Operations (nsfilemanager) combined with a small album example.
SDK upgrades, taking photos, and selecting images from the album have undergone minor changes, such as the callback method of uiimagepickercontrollerdelegate. A demo is used to briefly introduce the implementation process. First, the image cropping function leverages the agsimpleimageeditorview project on GitHub. Not to mention, let's look at the demo implementation process step by step:


1. download the project on GitHub to your local computer and drag it into your project (provided that you have created a project). Because agsimpleimageeditorview does not support arc, you must configure it accordingly, set the compiler tag-fno-objc-arc:



In addition, because image processing and image processing are used, two additional libraries must be imported, such


After compilation, Run Command + B to compile the Code. If no problem occurs, it indicates that the project integration is successful. Now we can start encoding. If not, check the error source, whether the above steps are complete.


Code Section: The following are all key codes. The specific details are not listed. The comments are very detailed and will not be repeated.


2. create the passimagedelegate protocol as a proxy for transferring values between the display interface and the intercept interface (this demo uses two value passing methods, if you are not familiar with this, refer to "iOS Study Notes 30-passing values between two viewcontrollers (1)") and create captureviewcontroller as the module for image capturing. Part of the passimagedelegate code is as follows:

#import <Foundation/Foundation.h>@protocol PassImageDelegate <NSObject>-(void)passImage:(UIImage *)image;@end

Captureviewcontroller. H is a part of the key code, mainly used to initialize the screenshot interface and process the screenshot after successful interception:

-(Void) viewdidload {[Super viewdidload]; // Add navigation bar and complete button uinavigationbar * navibar = [[uinavigationbar alloc] initwithframe: cgrectmake (0, 0,320, 44)]; [self. view addsubview: navibar]; uinavigationitem * naviitem = [[uinavigationitem alloc] initwithtitle: @ "image cropping"]; [navibar pushnavigationitem: naviitem animated: Yes]; // Save the button uibarbuttonitem * doneitem = [[uibarbuttonitem alloc] initwithtitle: @ "done" style: uibarbuttonitemstyleplain target: Self action: @ selector (savebutton)]; naviitem. rightbarbuttonitem = doneitem; // image is the image resource editorview = [[agsimpleimageeditorview alloc] initwithimage: Self. image]; editorview. frame = cgrectmake (0, 0, self. view. frame. size. width, self. view. frame. size. width); editorview. center = self. view. center; // The width and color of the outer border editorview. borderwidth = 1.f; editorview. bordercolor = [uicolor blackcolor]; // The width and color of the screenshot editorview. ratioviewborderwidth = 5.f; editorview. ratioviewbordercolor = [uicolor orangecolor. /2. 16. /9. 4. /3 .) editorview. ratio = 1; [self. view addsubview: editorview];} // The screenshot is completed-(void) savebutton {// output is the captured image. The uiimage type is uiimage * resultimage = editorview. output; // return it to the previous interface through a proxy to display [self. delegate passimage: resultimage]; [self dismissmodalviewcontrolleranimated: Yes];}

3. Open the Option List on the main interface and choose to take a photo or select the image code from the album:

// Select image source in the pop-up list-(ibaction) chosebuttonclicked :( ID) sender {uiactionsheet * chooseimagesheet = [[uiactionsheet alloc] initwithtitle: Nil delegate: Self cancelbuttontitle: @ "cancel" destructivebuttontitle: Nil otherbuttontitles: @ "camera", @ "photo library", nil]; [chooseimagesheet showinview: Self. view] ;}# Pragma mark upload method-(void) actionsheet :( uiactionsheet *) actionsheet clickedbuttonatindex :( nsinteger) buttonindex {uiimagepickercontroller * picker = [[uiimagepickercontroller alloc] init]; picker. delegate = self; Switch (buttonindex) {Case 0: // take picture if ([uiimagepickercontroller issourcetypeavailable: uiimagepickercontrollersourcetypecamera]) {picker. sourcetype = uiimagepickercontrollersourcetypecamera;} else {nslog (@ "camera cannot be turned on");} [self presentmodalviewcontroller: picker animated: Yes]; break; Case 1: // from album picker. sourcetype = uiimagepickercontrollersourcetypephotolibrary; [self presentmodalviewcontroller: picker animated: Yes]; break; default: break ;}}

Callback method after taking a photo or selecting an image:

# Pragma photo selection method-(void) imagepickercontroller :( uiimagepickercontroller *) picker didfinishpickingmediawithinfo :( nsdictionary *) info {[uiapplication sharedapplication]. statusbarhidden = no; nsstring * mediatype = [info objectforkey: uiimagepickercontrollermediatype]; nsdata * data; If ([mediatype isequaltostring: @ "public. image "]) {// do not directly use originimage, because this is an image data that has not been formatted and may lead to incorrect image or distortion, from the origin in uiimagepickercontrolleroriginalimage, we can see that it is very primitive. Haha uiimage * originimage = [info objectforkey: uiimagepickercontrolleroriginalimage]; // The image is compressed because the source image is large, you do not need to upload the source image uiimage * scaleimage = [self scaleimage: originimage toscale: 0.3]; // The following two steps are time-consuming operations. It is best to open a HUD to notify the user, this will improve the user experience and avoid blocking the interface if (uiimagepngrepresentation (scaleimage) = nil) {// convert the image to JPG format binary data = uiimagejpegrepresentation (scaleimage, 1 );} else {// convert the image to PNG binary data Data = uiimagepngrepresentation (scaleimage);} // generate a uiimage * image = [uiimage imagewithdata: Data]; // pass the image to the screenshot interface for screenshot and set the callback method (Protocol) captureviewcontroller * captureview = [[captureviewcontroller alloc] init]; captureview. delegate = self; captureview. image = image; // hide the menu bar picker of uiimagepickercontroller. navigationbar. hidden = yes; [picker pushviewcontroller: captureview animated: Yes];}

Callback method to display the captured image

# Pragma mark-image callback protocol method-(void) passimage :( uiimage *) image {// display the captured image on the main interface imageview. Image = image ;}

The last step is to scale the image:

# Pragma mark-zoom image-(uiimage *) scaleimage :( uiimage *) image toscale :( float) scalesize {uigraphicsbeginimagecontext (cgsizemake (image. size. width * scalesize, image. size. height * scalesize); [Image drawinrect: cgrectmake (0, 0, image. size. width * scalesize, image. size. height * scalesize)]; uiimage * scaledimage = uigraphicsgetimagefromcurrentimagecontext (); uigraphicsendimagecontext (); Return scaledimage ;}

Run the command on the real machine. The result is as follows:



After taking the photo, select the image and go to the cropping page. After cropping, the cropping result is displayed:


To join our QQ group or public account, see: Ryan's
Zone public account and QQ Group


I think the article is useful to you. Please pay attention to my Sina Weibo and talk to me: @ Tang Ren _ Ryan

Download project: Demo source code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.