phonegap下封装ios照片拍照、选取、裁剪、上传接口

说明:1、选择框可以采用UIAlertView(弹出框)和UIActionSheet(上拉框)两种形式,具体看个人喜好

            2、裁剪功能用AGSimpleImageEditorView实现,具体头文件和源文件可以到网上下载

            3、上传功能用ASIHTTPRequest实现,具体头文件和源文件可以到网上下载

            4、AGSimpleImageEditorView和ASIHTTPRequest均不支持arc,在Tagets->Build Phases->Compile Sources下 的相关文件,添加-fno-objc-arc

            5、在Tagets->Build Phases->Link Binary With Libraries下添加相关framework

源码:
ImageUploadPlugin.h

#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
#import "AGSimpleImageEditorView.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"
#import "Header.h"


@interface ImageUploadPlugin : CDVPlugin<UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,ASIHTTPRequestDelegate>


@property (nonatomic,strong) UIAlertView* imageAlertView;
@property (nonatomic,strong) UIImagePickerController * imagePickerController;
@property (nonatomic,strong) NSString * imagePath;
@property (nonatomic,strong) UIView * imageView;
@property (nonatomic,strong) AGSimpleImageEditorView * agsimp;
@property (nonatomic,strong) UIImage * savedImage;
@property (nonatomic,strong) NSString * imageDataStr;
@property (nonatomic,strong) UIActionSheet * imageActionSheet;
@property (nonatomic,strong) NSThread* thread;
@property (nonatomic,strong) CDVInvokedUrlCommand* imageCommand;
@property (nonatomic,assign) float imageRatio;
@property (nonatomic,strong) SBJsonParser * parser;
@property (nonatomic,strong) ASIFormDataRequest * globalRequest;
@property (nonatomic,assign) BOOL cutFlag;

/*
 * 选择获取图片
 */
-(void)selectImageNoCut:(CDVInvokedUrlCommand*) command;

/*
 * 选择、裁剪图片
 */
-(void)selectImage:(CDVInvokedUrlCommand*) command;


/*
 * 上传图片
 */
-(void)uploadImage:(CDVInvokedUrlCommand*) command;

@end

ImageUploadPlugin.m

#import "ImageUploadPlugin.h"

@implementation ImageUploadPlugin

@synthesize imageAlertView,imagePickerController,imagePath,imageView,agsimp,savedImage,imageDataStr,imageActionSheet,thread,imageCommand,imageRatio,parser,globalRequest,cutFlag,file_key;


-(void) pluginInit
{
    savedImage = [[UIImage alloc]init];
    imagePath = @"";
    imageDataStr = @"";
    imageRatio = 1;
    cutFlag = NO;
    file_key = @"";
}



/*
 * 选择、裁剪图片
 */
-
(void)selectImage:(CDVInvokedUrlCommand*) command
{
    [self pluginInit];
    cutFlag = YES;
    imageCommand = command;
    NSString* echo = [command.arguments objectAtIndex:0];
    if (echo != nil && [echo length] > 0) {
        
        NSArray* array = [echo componentsSeparatedByString:@","];
        if (array.count == 2) {
            
            NSString* imageWidth = array[0];
            NSString* imageHeight = array[1];
            
            imageRatio = ([imageWidth floatValue]/[imageHeight floatValue]);
        }
    }
    
    imageAlertView = [[UIAlertView alloc]initWithTitle:@"图片来源" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"相册选取", nil];
    [imageAlertView show];

}

-(void)selectImageNoCut:(CDVInvokedUrlCommand*) command
{
    [self pluginInit];
    imageCommand = command;
    imageAlertView = [[UIAlertView alloc]initWithTitle:@"图片来源" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"相册选取", nil];
    [imageAlertView show];
}

/*
 * 上传图片
 */
-(void)uploadImage:(CDVInvokedUrlCommand*) command
{
    NSString* uploadUrl = @"";
    imageCommand = command;
    NSString* echo = [command.arguments objectAtIndex:0];
    if (echo != nil && [echo length] > 0) {
        
        NSArray* array = [echo componentsSeparatedByString:@","];
        if (array.count == 2) {
            
            uploadUrl = array[0];
            file_key = array[1];
            
            //检查url中是否包含key
            NSString* keyFlag = @"&key=";
            BOOL bKeyFlag = NO;
            NSRange range = [uploadUrl rangeOfString:keyFlag];
            if (range.length > 0) {
                bKeyFlag = YES;
            }
            
            //上传文件相关设置
            globalRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:uploadUrl]];
            //[globalRequest setShouldAttemptPersistentConnection:NO];
            
            if (!bKeyFlag) {
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                NSString* userKey = [userDefaults objectForKey:@"userKey"];
                [globalRequest setPostValue:userKey forKey:@"key"];
            }
            
            globalRequest.delegate = self;
            [globalRequest addFile:imagePath forKey:@"file"];
            globalRequest.defaultResponseEncoding = NSUTF8StringEncoding;
            [globalRequest setTimeOutSeconds:UPLOAD_TIMEOUT_SECONDS];
            [globalRequest setDidFinishSelector:@selector(imageUploadFinish:)];
            [globalRequest setDidFailSelector:@selector(imageUploadFail:)];
            [globalRequest startAsynchronous];
        }
    }
    
    
    
    
    
}

-(void)imageUploadFinish:(ASIHTTPRequest*)request
{
    CDVPluginResult* pluginResult = nil;
    //NSLog(@"%@",[globalRequest responseString]);
    
    parser = [[SBJsonParser alloc]init];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithDictionary:[parser objectWithString:[request responseString]]];
    NSString* code = [NSString stringWithFormat:@"%@",[dic objectForKey:@"code"]];
    NSString* msg = @"";
    if([code isEqualToString:@"200"]){
        NSString* dataStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"data"]];
        NSString* returnJson = [self getUploadFileRetunJson:dataStr];
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:returnJson];

    }else{
        //msg = [dic objectForKey:@"msg"];
        //msg= [msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:file_key];
    }

    [self.commandDelegate sendPluginResult:pluginResult callbackId:imageCommand.callbackId];
}

-(void) imageUploadFail:(ASIHTTPRequest*)request
{
    CDVPluginResult* pluginResult = nil;
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:file_key];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:imageCommand.callbackId];
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==0){
        [self showCamera];
    }else if(buttonIndex==1){
        [self showGallery];
    }else{
    }
}
    
    

/*
 * 选择框点击事件
 */
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex is : %li",(long)buttonIndex);
    switch (buttonIndex) {
        case 0:{
            
        }break;
        case 1:{
            [self showCamera];
        }break;
        case 2:{
            [self showGallery];
        }break;
        default:
            break;
    }
}

-(void)showCamera
{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.delegate = self;
        [self.viewController.view addSubview: imagePickerController.view];

    }else{
        NSLog(@"相机不能用。。。");
    }
        
    
}

-(void)showGallery
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.delegate = self;
        [self.viewController.view addSubview: imagePickerController.view];
        
    }else{
        NSLog(@"相册不能用。。。");
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    @try {
        
        imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"wnsImage.png"];
        
        //[picker dismissViewControllerAnimated:YES completion:^{
            if (cutFlag) {
                [self imageCut:picker didFinishPickingMediaWithInfo:info];
            }else{
                [self saveImage:picker didFinishPickingMediaWithInfo:info];
            }
        //}];
        
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
    
}

-(void)imageCut:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    UIImage * images = [self scaleImage:image ToScale:0.5];
    imageView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [imageView setBackgroundColor:[UIColor blackColor]];
    agsimp = [[AGSimpleImageEditorView alloc]initWithImage:images];
    agsimp.frame =CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-30);
    //外边框颜色宽度
    agsimp.borderColor = [UIColor blackColor];
    agsimp.borderWidth= 1.0f;
    //截取框颜色宽度
    agsimp.ratioViewBorderColor = [UIColor darkGrayColor];
    agsimp.ratioViewBorderWidth = 4.0f;
    //截取百分比
    agsimp.ratio = imageRatio;
    [imageView addSubview:agsimp];
    UIButton*but = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    but.frame =CGRectMake(20, [UIScreen mainScreen].bounds.size.height-30, [UIScreen mainScreen].bounds.size.width-40, 30);
    [but setTitle:@"保存" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(saveCutImage) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:but];
    [self.viewController.view addSubview:imageView];
    [self.viewController.view bringSubviewToFront:imageView];
    


}

-(void)saveCutImage
{
    @try {
        savedImage =agsimp.output;
        NSData * data = UIImagePNGRepresentation(savedImage);
        [data writeToFile:imagePath atomically:YES];
        imageDataStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        //[self.viewController.view sendSubviewToBack:imageView];
        
        [imageView removeFromSuperview];
        [imagePickerController.view removeFromSuperview];
        
        NSString* returnStr = [self getImageReturnJson];
        CDVPluginResult* pluginResult = nil;
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:returnStr];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:imageCommand.callbackId];
        
    }
    @catch (NSException *exception) {
        
    }
    @finally {

    }
    
}

-(void)saveImage:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    @try {
        savedImage = info[UIImagePickerControllerOriginalImage];
        savedImage = [self scaleImage:savedImage ToScale:0.5];
        
        NSData * data = UIImagePNGRepresentation(savedImage);
        [data writeToFile:imagePath atomically:YES];
        imageDataStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        
        //[self.viewController.view sendSubviewToBack:imageView];
        [imageView removeFromSuperview];
        [imagePickerController.view removeFromSuperview];
        
        NSString* returnStr = [self getImageReturnJson];
        //NSLog(@"%@",returnStr);
        CDVPluginResult* pluginResult = nil;
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:returnStr];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:imageCommand.callbackId];
        
        
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
    
}

-(NSString*) getImageReturnJson
{
    NSString* returnJson = @"{\"imageInfo\":";
    returnJson =  [returnJson stringByAppendingString:@"{"];
    returnJson = [returnJson stringByAppendingString:@"\"path\":\""];
    returnJson = [returnJson stringByAppendingString:imagePath];
    returnJson = [returnJson stringByAppendingString:@"\","];
    returnJson = [returnJson stringByAppendingString:@"\"text\":\""];
    returnJson = [returnJson stringByAppendingString:imageDataStr];
    returnJson = [returnJson stringByAppendingString:@"\","];
    returnJson = [returnJson stringByAppendingString:@"\"width\":\""];
    
    float imageWidth = savedImage.size.width;
    NSString* stringWidth = [NSString stringWithFormat:@"%f",imageWidth];
    returnJson = [returnJson stringByAppendingString:stringWidth];
    returnJson = [returnJson stringByAppendingString:@"\","];
    
    returnJson = [returnJson stringByAppendingString:@"\"height\":\""];
    float imageHeight = savedImage.size.height;
    NSString* stringHeight = [NSString stringWithFormat:@"%f",imageHeight];
    returnJson = [returnJson stringByAppendingString:stringHeight];
    returnJson = [returnJson stringByAppendingString:@"\"}}"];
    
    return returnJson;
    
}

-(NSString*) getUploadFileRetunJson:(NSString*) dataStr
{
    NSString* returnJson = @"{\"uploadFileInfo\":";
    returnJson =  [returnJson stringByAppendingString:@"{"];
    returnJson = [returnJson stringByAppendingString:@"\"data\":\""];
    returnJson = [returnJson stringByAppendingString:dataStr];
    returnJson = [returnJson stringByAppendingString:@"\","];
    returnJson = [returnJson stringByAppendingString:@"\"file_key\":\""];
    returnJson = [returnJson stringByAppendingString:file_key];
    returnJson = [returnJson stringByAppendingString:@"\"}}"];
    
    return returnJson;
}



-(UIImage*)scaleImage:(UIImage*)images ToScale:(float)scalesize{
    CGSize  size = CGSizeMake(images.size.width*scalesize, images.size.height*scalesize);
    UIGraphicsBeginImageContext(size);
    [images drawInRect:CGRectMake(0, 0, images.size.width*scalesize, images.size.height*scalesize)];
    UIImage * scaleImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaleImage;
}

@end


 

index.html

function getImageData()
        {
            cordova.exec(imageSuccess,imageError,'ImageUploadPlugin','selectImage',['3,1']);
        }
        
        function getImageData()
        {
            cordova.exec(imageSuccess,imageError,'ImageUploadPlugin','selectImageNoCut',[]);
        }

        
        function imageSuccess(result){
            var jsonResult =  eval('(' + result + ')');
            var src = 'data:image/png;base64,'+jsonResult.imageInfo.text;
            var Str=document.getElementById("list");
            Str.innerHTML="<img src='"+src+"' id='addLogoid'>"; //预览图片的位置
            document.getElementById("addLogoid").style.width="120px";
            document.getElementById("addLogoid").style.height="120px";
            document.getElementById("storagelogo").value="true";
            
            cordova.exec(uploadSuccess,uploadError,'ImageUploadPlugin','uploadImage',['http://192.168.0.127:8080/mobile/index.php?act=upload&op=save_file']);
        
        }
        
        function imageError(error){
            alert(error);
        }
        
        
        function uploadSuccess(result){
            alert(result);
        }
        
        function uploadError(error){
            alert(error);
        }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值