iOS camera/album Get pictures, Compress pictures, upload server method summary

Source: Internet
Author: User

Album

The iphone album contains some photos of camera roll + user computer syncing. Users can select an image from an album by using the interactive dialog box provided by the Uiimagepickercontroller class. However, note: The picture Machine path in the album cannot be accessed directly from the application, only through the end user to select and use the photo album

Application Package

An application package may store images with executable programs, info.plist files, and other resources. We can read these package-based images through the local file path and display them in the application.

Sand box

With the sandbox, we can store images in documents, libraries, and TMP folders. These files can have application reads, and images can be created from file paths. Although the outside of the sandbox is technically feasible, Apple indicates that these parts are not within the scope of the AppStore application.

Internet

Applications can access resources on the Internet through the URL of the picture.

The above for some small knowledge, from the "iphone Development Cheats (second edition)", you can refer to this book yourself.

The following starts to cut to the chase, from the camera/album to get pictures, compress pictures, upload pictures.

Get pictures from Camera/album

Just mentioned in the above knowledge from the camera/album to get the picture is for the end user, by the user to browse and select the image for the program to use. Here we need the Uiimagepickercontroller class to interact with the user.

Using Uiimagepickercontroller and user interaction, we need to implement 2 protocols.

View Code

The code is as follows

#pragma mark gets the active picture from the user album

-(void) pickimagefromalbum

{

Imagepicker = [[Uiimagepickercontroller alloc] init];

Imagepicker.delegate = self;

Imagepicker.sourcetype = uiimagepickercontrollersourcetypephotolibrary;

Imagepicker.modaltransitionstyle = uimodaltransitionstylecoververtical;

imagepicker.allowsediting = YES;

[Self presentmodalviewcontroller:imagepicker animated:yes];

}

Let's take a look at the above to get the picture from the album, we first instantiate the Uiimagepickercontroller object, then set the Imagepicker object as the current object, Set Imagepicker's picture source as Uiimagepickercontrollersourcetypephotolibrary, indicating that the current picture is from a photo album, in addition to setting whether the user can edit the picture.

View Code

The code is as follows

#pragma mark gets the active picture from the camera

-(void) Pickimagefromcamera

{

Imagepicker = [[Uiimagepickercontroller alloc] init];

Imagepicker.delegate = self;

Imagepicker.sourcetype = Uiimagepickercontrollersourcetypecamera;

Imagepicker.modaltransitionstyle = uimodaltransitionstylecoververtical;

imagepicker.allowsediting = YES;

[Self presentmodalviewcontroller:imagepicker animated:yes];

}

The above is from the camera to get pictures, and from the album to get pictures just picture source settings are not the same, the camera image from the source for Uiimagepickercontrollersourcetypecamera.

After interacting with the user, the user selects a good picture and then recalls the method of selecting end.

View Code

The code is as follows

-(void) Imagepickercontroller: (Uiimagepickercontroller *) Picker Didfinishpickingmediawithinfo: (NSDictionary *) info

{

UIImage *image= [Info objectforkey:@ "Uiimagepickercontrolleroriginalimage"];

if (Picker.sourcetype = = Uiimagepickercontrollersourcetypecamera)

{

Uiimagewritetosavedphotosalbum (image, nil, nil, nil);

}

Theimage = [Utilmethod imagewithimagesimple:image scaledtosize:cgsizemake (120.0, 120.0)];

UIImage *midimage = [Utilmethod imagewithimagesimple:image scaledtosize:cgsizemake (210.0, 210.0)];

UIImage *bigimage = [Utilmethod imagewithimagesimple:image scaledtosize:cgsizemake (440.0, 440.0)];

[Theimage retain];

[Self saveimage:theimage withname:@ "salesimagesmall.jpg"];

[Self saveimage:midimage withname:@ "salesimagemid.jpg"];

[Self saveimage:bigimage withname:@ "salesimagebig.jpg"];

[Self dismissmodalviewcontrolleranimated:yes];

[Self refreshdata];

[Picker release];

}

At the end of the callback method, we handle the size of the image and prepare the image for uploading.

Zoom picture

Zooming the picture is simple, put the code directly, let us refer to it.

View Code

The code is as follows

Compress pictures

+ (uiimage*) Imagewithimagesimple: (uiimage*) Image scaledtosize: (cgsize) newSize

{

Create a graphics image context

Uigraphicsbeginimagecontext (newSize);

Tell the old image to draw in this new context, with the desired

New size

[Image Drawinrect:cgrectmake (0,0,newsize.width,newsize.height)];

Get the new image from the context

uiimage* newimage = Uigraphicsgetimagefromcurrentimagecontext ();

End the context

Uigraphicsendimagecontext ();

Return the new image.

return newimage;

}

Storing images

In the above we obtained the picture and compressed the picture, through the previous knowledge, the application needs to save some of the pictures to sandbox is a good choice, and the application can go directly through the path to the method sandbox picture, where we put the picture in the sandbox in the documents directory.

View Code

The code is as follows

#pragma mark save picture to document

-(void) SaveImage: (UIImage *) tempimage withname: (NSString *) imageName

{

nsdata* imageData = uiimagepngrepresentation (tempimage);

nsarray* paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);

nsstring* documentsdirectory = [Paths objectatindex:0];

Now we get the full path to the file

nsstring* fullpathtofile = [Documentsdirectory stringbyappendingpathcomponent:imagename];

And then we write it out

[ImageData Writetofile:fullpathtofile Atomically:no];

}

Get pictures from the documents directory

To get the picture from the documents below, we first need to get the path to the documents directory.

View Code

The code is as follows

#pragma mark gets the documents path from the document directory

-(NSString *) Documentfolderpath

{

return [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents"];

}

Then, we can access the resource by the file name.

View Code

Upload image

In the project we used the Asiformhttprequest open source framework, and some of the HTTP request code is as follows, and the HTTP return and related callback methods are omitted.

View Code

The code is as follows

-(void) Uploadsalesbigimage: (NSString *) bigimage midimage: (NSString *) midimage smallimage: (NSString *) SmallImage

{

Nsurl *url = [Nsurl Urlwithstring:upload_server_url];

Asiformdatarequest *request = [Asiformdatarequest Requestwithurl:url];

[Request setpostvalue:@ "photo" forkey:@ "type"];

[Request Setfile:bigimage forkey:@ "File_pic_big"];

[Request Buildpostbody];

[Request Setdelegate:self];

[Request Settimeoutseconds:time_out_seconds];

[Request startasynchronous];

}

Call the iOS album from UIWebView and select the image to upload to the Linux Web server. (2012-08-09 17:03:29) reproduced
Tags: UIWebView Upload to Server iOS Development Category: Ios
====== First Look at the following iOS end ======= ViewController.h

//

ViewController.h

Xcode_fileupload

//

Created by Kirssu Ryu on 12-8-7.

Copyright (c) 2012 __jmodule__. All rights reserved.

//

#import

Uiwebviewdelegate proxy class: Pass value to JavaScript.

Uinavigationcontrollerdelegate,uiimagepickercontrollerdelegate proxy class: Open a series of operations such as albums.

@interface Viewcontroller:uiviewcontroller<</span>uiwebviewdelegate,uinavigationcontrollerdelegate, uiimagepickercontrollerdelegate>{

UIWebView *mywebview;

Uiimagepickercontroller *picker_library_;

}

My WebView control

@property (nonatomic, retain) iboutlet UIWebView *mywebview;

Variables for album classes

@property (nonatomic, retain) Iboutlet Uiimagepickercontroller *picker_library_;

@end

VIEWCONTROLLER.M

//

ViewController.h

Xcode_fileupload

//

Created by Kirssu Ryu on 12-8-7.

Copyright (c) 2012 __jmodule__. All rights reserved.

//

#import "ViewController.h"

@interface Viewcontroller ()

@end

@implementation Viewcontroller

@synthesize Mywebview;

@synthesize Picker_library_;

-(void) viewdidload

{

[Super Viewdidload];

Agent Uiwebviewdelegate

Mywebview.delegate = self;

Set the link to load

Nsurl *url = [Nsurl urlwithstring:@ "http://*****/test/index.php"];

Create a Request object

Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

Send the request to the WebView to achieve the display content

[Mywebview Loadrequest:request];

}

-(void) viewdidunload

{

[Self setmywebview:nil];

[Super Viewdidunload];

Release any retained subviews of the main view.

}

-(BOOL) Shouldautorotatetointerfaceorientation: (uiinterfaceorientation) interfaceorientation

{

Return (interfaceorientation! = Uiinterfaceorientationportraitupsidedown);

}

Get the value from the website

#pragma mark--

#pragma Mark Uiwebviewdelegate

-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype {

The URL that gets the request, the first is the path, and when you click the button on the Web, you get the path through the web.

NSString *requeststring = [[Request URL] absolutestring];

Returns an array, based on the ":" Split string.

Nsarray *components = [requeststring componentsseparatedbystring:@ ":"];

If the element inside the array is greater than 1 and the value of the first element is equal

if ([Components Count] > 1 && [(NSString *) [objectatindex:0] isequaltostring:@ "Gallery"]) {

if ([(NSString *) [Components objectatindex:1] isequaltostring:@ "open"])

{

[Self opengallery];

}

return NO;

}

return YES;

}

Open album

-(void) opengallery{

Initialize class

Picker_library_ = [[Uiimagepickercontroller alloc] init];

Specify several total picture sources

Uiimagepickercontrollersourcetypephotolibrary: Indicates that all photos are displayed.

Uiimagepickercontrollersourcetypecamera: Indicates that a photo is selected from the camera.

Uiimagepickercontrollersourcetypesavedphotosalbum: Indicates that only photos are selected from the album.

Picker_library_.sourcetype = uiimagepickercontrollersourcetypephotolibrary;

Indicates that the user can edit the picture.

picker_library_.allowsediting = YES;

Agent

Picker_library_.delegate = self;

[Self Presentmodalviewcontroller:picker_library_

Animated:yes];

}

3.x callback after the user selects the picture

-(void) Imagepickercontroller: (Uiimagepickercontroller *) picker

Didfinishpickingmediawithinfo: (nsdictionary *) info

{

NSLog (@ "3.x");

Get the edited picture

uiimage* image = [info objectforkey: @ "Uiimagepickercontrollereditedimage"];

[Self dismissmodalviewcontrolleranimated:yes];

[Self imageupload:image];

}

2.x callback after the user selects the picture

-(void) Imagepickercontroller: (Uiimagepickercontroller *) Picker didfinishpickingimage: (UIImage *) Image Editinginfo :(nsdictionary *) editinginfo

{

NSLog (@ "2.x");

Nsmutabledictionary * dict= [nsmutabledictionary dictionarywithdictionary:editinginfo];

[Dict setobject:image forkey:@ "Uiimagepickercontrollereditedimage"];

Direct call to 3.x processing function

[Self imagepickercontroller:picker didfinishpickingmediawithinfo:dict];

}

User chooses to cancel

-(void) Imagepickercontrollerdidcancel: (Uiimagepickercontroller *) picker

{

[Self dismissmodalviewcontrolleranimated:yes];

}

Upload Image method

-(void) Imageupload: (UIImage *) image{

Convert images to imagedate format

NSData *imagedata = uiimagejpegrepresentation (image, 1.0);

Transfer path

NSString *urlstring = @ "http://*****/test/upload.php";

Create Request Object

Nsmutableurlrequest * request = [[Nsmutableurlrequest alloc] init];

Set Request Path

[Request Seturl:[nsurl urlwithstring:urlstring];

Request method

[Request sethttpmethod:@ "POST"];

A series of upload header tags

NSString *boundary = [NSString stringwithstring:@ "---------------------------14737809831466499882746641449"];

NSString *contenttype = [NSString stringwithformat:@ "multipart/form-data; boundary=%@", boundary];

[Request Addvalue:contenttype Forhttpheaderfield: @ "Content-type"];

Nsmutabledata *body = [Nsmutabledata data];

[Body appenddata:[[nsstring stringwithformat:@ "\r\n--%@\r\n", boundary]datausingencoding:nsutf8stringencoding]];

[Body appenddata:[[nsstring stringwithstring:@ "content-disposition:form-data; name=" UserFile "; filename=" vim_ Go.jpg "\ r \ n"] datausingencoding:nsutf8stringencoding];

[Body appenddata:[[nsstring stringwithstring:@ "content-type:application/octet-stream\r\n\r\n"]dataUsingEncoding: Nsutf8stringencoding]];

[Body Appenddata:[nsdata Datawithdata:imagedata];

[Body appenddata:[[nsstring stringwithformat:@ "\r\n--%@--\r\n", Boundary]datausingencoding:nsutf8stringencoding]] ;

[Request Sethttpbody:body];

Upload file start

NSData *returndata = [nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil];

Get return value

NSString *returnstring = [[NSString alloc] Initwithdata:returndata encoding:nsutf8stringencoding];

NSLog (@ "%@", returnstring);

}

@end

======ios end, and then look at the web-side ======= index.phpfunction uploads () {SendCommand ("open");} function SendCommand (cmd) {var url = "Gallery:" +cmd;document.location = URL;} upload.php

iOS camera/album Get pictures, Compress pictures, upload server method summary

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.