IOS using AFN for single and multi-image upload camera/album Get pictures, Compress pictures

Source: Internet
Author: User
Tags dateformat

Images must be compressed when uploading, otherwise it will fail to upload

The first is to select pictures and videos with the system album. iOS system comes with UIImagePickerController , can choose or take pictures video, but the biggest problem is only support single, because the project requirements need to support multiple selection, can only be customized. There are two frameworks for getting the system library, one is ALAssetsLibrary compatible with iOS low, but not recommended in iOS9, and the other is PHAsset , but the minimum requirement is iOS8. Compatible to IOS7, you can choose theALAssetsLibrary 现在我们先说选择一张图的情况

One, single graph multi-image upload

1. Single image upload

Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager]; [Manager post:urlstring Parameters:params constructingbodywithblock:^ (id_nonnull formData) {

Use date to generate picture name

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

Formatter.dateformat = @ "Yyyy-mm-dd HH:mm:ss";

NSString *filename = [NSString stringwithformat:@ "%@.png", [Formatter stringfromdate:[nsdate Date]];

[FormData appendpartwithfiledata:imagedata name:@ "UploadFile" Filename:filename mimetype:@ "Image/png"];

} success:^ (Afhttprequestoperation * _nonnull operation, id _nonnull responseobject) {

Upload image successfully executed callback

Completion (RESPONSEOBJECT,NIL);

} failure:^ (Afhttprequestoperation * _nonnull operation, Nserror * _nonnull error) {

Upload image failed to execute callback

Completion (NIL,ERROR);

}];

2. Multi-image upload

The difference between multi-image uploads and single-image uploads is the file name

Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager]; [Manager post:urlstring Parameters:params constructingbodywithblock:^ (id_nonnull formData) {

Nsinteger imgcount = 0;

For (NSData *imagedata in Imagedatas) {

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

Formatter.dateformat = @ "Yyyy-mm-dd HH:mm:ss:SSS";

NSString *filename = [NSString stringwithformat:@ "%@%@.png", [Formatter stringfromdate:[nsdate date]],@ (ImgCount)];

[FormData appendpartwithfiledata:imagedata name:[nsstring stringwithformat:@ "uploadfile%@", @ (Imgcount)] FileName:filename mimetype:@ "Image/png"];

imgcount++;

}

} success:^ (Afhttprequestoperation * _nonnull operation, id _nonnull responseobject) {

Completion (RESPONSEOBJECT,NIL);

} failure:^ (Afhttprequestoperation * _nonnull operation, Nserror * _nonnull error) {

Completion (NIL,ERROR);

}];

Second, get pictures, compress pictures

When getting pictures from a camera/album We need to Uiimagepickercontroller class to interact with users using uiimagepickercontroller and user interaction, we need to implement 2 protocols < Uiimagepickercontrollerdelegate,uinavigationcontrollerdelegate>

1. Get the picture (from the album or the camera)

1.1 We first instantiate the Uiimagepickercontroller object and then set the Imagepicker object as the current object, Set Imagepicker's picture source to Uiimagepickercontrollersourcetypephotolibrary, indicating that the current picture is from the album, in addition to the user can also set the picture can be edited

#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];
}

1.2 and get pictures from the album just the picture source settings are not the same, the camera image from the source for Uiimagepickercontrollersourcetypecamera

#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];
}

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

-(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)];
[Self saveimage:theimage withname:@ "salesimagesmall.jpg"];
[Self saveimage:midimage withname:@ "salesimagemid.jpg"];
[Self saveimage:bigimage withname:@ "salesimagebig.jpg"];

[Self dismissmodalviewcontrolleranimated:yes];
[Self refreshdata];
}

At the end of the callback method, we handle the size of the image and prepare the image for uploading. Zooming a picture to zoom a picture is relatively simple

Compress picture (zoom picture)
+ (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

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

#pragma mark gets the documents path from the document directory
-(NSString *) Documentfolderpath
{
return [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents"];
}

Then we can go through the file name to access the resource.

Add: IOS image compression processing

First, we must make clear that the image compression is actually two concepts:

    1. "Pressure" refers to the size of the file is smaller, but the number of pixels unchanged, the length and width of the dimensions are unchanged, then the quality may fall.
    2. "Shrink" refers to the size of the file is smaller, that is, the number of pixels reduced, and the size of the long-width smaller, the file volume will also be reduced.
Picture "Press" processing

For the function of "pressure", we can use UIImageJPEGRepresentation or UIImagePNGRepresentation implement the method, such as:

NSData *imgData = UIImageJPEGRepresentation(image, 0.5);

The first parameter is the picture object, the second parameter is the coefficient of pressure, and its value range is 0~1.

UIImageJPEGRepresentationThe official comment for the method is: return image as JPEG. May return nil If image has no cgimageref or invalid bitmap format. Compression is 0 (most): 1 (least)

About PNG and JPEG format compression
    1. UIImageJPEGRepresentationThe function requires two parameters: a reference to a picture and a compression factor, but UIImagePNGRepresentation only a picture reference as a parameter.

    2. UIImagePNGRepresentation(UIImage \*image)is much UIImageJPEGRepresentation(UIImage* image, 1.0) larger than the amount of picture data returned.

In the same picture, the amount of data returned is the size of the volume, and UIImagePNGRepresentation(image) 199K UIImageJPEGRepresentation(image, 1.0) The amount of data returned is only 140K , less than the former 59K .

If the sharpness of the picture is not very high, it is recommended UIImageJPEGRepresentation to use, can greatly reduce the amount of image data. For example, the image you just shot, UIImageJPEGRepresentation(image, 1.0) when you read the data by calling, returns the size of the data, 140K but when you change the compression factor to 0.5 read the data again, The size of the returned data only 11K , greatly compressed the image of the amount of data, and there is no difference in clarity, the quality of the picture is not significantly reduced. Therefore, when reading the image data content, it is recommended to use first UIImageJPEGRepresentation , and according to their actual use of the scene, set the compression coefficient, further reduce the size of the image data.

Tip: The compression coefficient should not be too low, usually 0.3~0.7, too small may appear black edge and so on.

Let's take a look at UIImageJPEGRepresentation the data tables used by the author:


Image

The author has counted the iphone full screen image and the size of the original image before and after compression, and we need to decide which compression factor to choose according to the sharpness of the image after compression on the PC.

Picture "pinch" processing

With the [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)] ability to "shrink" the picture. The following is the size of the picture I shrink api :

/*! * @author Huangyi, 15-12-01 16:12:01 * * Compress the image to the target size * * @param sourceimage source picture * @param targetwidth the width of the final size of the picture * * @return return Back to the width and height of the source image to compress to the target width, height of the picture */-(UIImage *) Compressimage: (UIImage *) Sourceimage totargetwidth: (CGFloat) Targetwidth {cgsize imageSize = Sourceimage.size; cgfloat width = imagesize.width; cgfloat height = imagesize.height; cgfloat targetheight = (targetwidth/width) * height; uigraphicsbeginimagecontext (CGSizeMake (TargetWidth, Targetheight)); [Sourceimage drawinrect:cgrectmake (0, 0, Targetwidth, Targetheight)]; uiimage *newimage =  Uigraphicsgetimagefromcurrentimagecontext (); uigraphicsendimagecontext (); return newimage;}            

We only "pressure" the picture and not shrink, sometimes it is not up to our needs. Therefore, appropriate to the picture "shrink" a size, can meet our needs.

Tip: The width height of the full-screen image we get is not the width of the device, it is usually larger than the width of the set, and the height may be equal. We can take a panorama, then the width is very big.

IOS using AFN for single and multi-image upload camera/album Get pictures, Compress pictures

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.