相机

来源:互联网 发布:上海达观数据公司咋样 编辑:程序博客网 时间:2024/06/02 09:52

代码如下:

#import <UIKit/UIKit.h>


@interface ViewController :UIViewController<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak,nonatomic)IBOutletUIImageView *cameraImage;

- (IBAction)BtnClick:(id)sender;



#import "ViewController.h"


@interface ViewController (){

    BOOL isFullScreen;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}



//给判断是否要调用相机还是相册

- (IBAction)BtnClick:(id)sender {

    UIActionSheet *sheet;

    if ([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])//调用相机

    {

        sheet = [[UIActionSheetalloc]initWithTitle:@"选择"delegate:selfcancelButtonTitle:nildestructiveButtonTitle:@"取消"otherButtonTitles:@"拍照",@"从相册中选择" ,nil];

    }

    else{//调用相册

        sheet = [[UIActionSheetalloc]initWithTitle:@"选择"delegate:selfcancelButtonTitle:nildestructiveButtonTitle:@"取消"otherButtonTitles:@"从相册中选择",nil];

    }

    sheet.tag =255;

    [sheet showInView:self.view];

    

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if (actionSheet.tag ==255)

    {

        NSUInteger sourceType =0;//给一个标志用来判断选择的是相机还是相册

        if ([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

        {

            switch (buttonIndex)

            {

                case0:

                    return;

                    break;

                case1:

                    sourceType = UIImagePickerControllerSourceTypeCamera;

                    break;

                case2:

                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

                    break;

                    

                default:

                    break;

            }

        }

        else

        {

            if (buttonIndex ==0 )

            {

                return;

            }else

            {

                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

            }

        }

        UIImagePickerController *imagePickerController = [[UIImagePickerControlleralloc]init];

        

        //给相机设置代理

        imagePickerController.delegate =self;

        //应许编辑

        imagePickerController.allowsEditing =YES;

        imagePickerController.sourceType = sourceType;

        //模态跳转

        [selfpresentViewController:imagePickerControlleranimated:YEScompletion:^{

        }];

        

    }

   

}

#pragma mark - image picker delegte

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    

    [picker dismissViewControllerAnimated:YEScompletion:^{

    }];

    

    /* 此处info有六个值

     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)

     * UIImagePickerControllerOriginalImage;  // a UIImage原始图片

     * UIImagePickerControllerEditedImage;    // a UIImage裁剪后图片

     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)

     * UIImagePickerControllerMediaURL;       // an NSURL

     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework

     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured phot

     */

    UIImage *image = [infoobjectForKey:UIImagePickerControllerOriginalImage];


//把拍下来的照片保存到相册里

    UIImageWriteToSavedPhotosAlbum(image,self, nil,nil);


    

    //保存图片到本地

    [selfsaveImage:imagewithName:@"currentImage.png"];

    

    

    //获取沙河路径(就是照片存的路径)

    NSString *fullPath = [[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"currentImage.png"];

    

    //根据文件路径初始化照片

    UIImage *savedImage = [[UIImagealloc]initWithContentsOfFile:fullPath];

    

    //设置图片

    [self.cameraImagesetImage:savedImage];

    

    self.cameraImage.tag =100;


}

#pragma mark - image picker delegte

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{

    [selfdismissViewControllerAnimated:YEScompletion:^{

    }];

}



-(void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{

    

//高保真压缩图片方法

    NSData *imageData =UIImageJPEGRepresentation(currentImage,0.5);

    /*错误写法,要注意我们写到本地的是urlPath --->stringByAppendingPathComponent**/

//    NSString *fullPath = [[NSHomeDirectory()stringByAppendingString:@"Documents"]stringByAppendingString:imageName];

    

    

     // 获取沙盒目录

    NSString *fullPath = [[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:imageName];

    

    /**

     *  写入文件必须是以data类型的才行(所以我们要把image转化为data类型)

     *  将图片写入文件

     **/

    

    [imageData writeToFile:fullPathatomically:NO];

    

    


}


/**

 *点击放大缩小图片

 *

 */

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

  

    isFullScreen = !isFullScreen;


    UITouch *touch = [touchesanyObject];

  

    CGPoint touchPoint = [touchlocationInView:self.view];

    

    CGPoint imagePoint =self.cameraImage.frame.origin;

    

    //touchPoint.x touchPoint.y 就是触点的坐标

    

    // 触点在imageView内,点击imageView放大,再次点击时缩小

    

    if(imagePoint.x <= touchPoint.x && imagePoint.x +self.cameraImage.frame.size.width >=touchPoint.x && imagePoint.y <=  touchPoint.y && imagePoint.y+self.cameraImage.frame.size.height >= touchPoint.y)

        

    {

        

        // 设置图片放大动画

        

        [UIViewbeginAnimations:nilcontext:nil];

        

        // 动画时间

        

        [UIViewsetAnimationDuration:1];

       

        if (isFullScreen) {

            

            // 放大尺寸

            

            self.cameraImage.frame =CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);


        }

        else {

            // 缩小尺寸

            self.cameraImage.frame =CGRectMake(50,65,90,115);

        }

       

        // commit动画

    

        [UIViewcommitAnimations];

           }

   }


/*

 - (IBAction)uploadImage

  {

 

       此段代码如果需要修改,可以调整的位置

 

       1. upload.php改成网站开发人员告知的地址

       2. file改成网站开发人员告知的字段名

 

     // 1. httpClient->url


     // 2. 上传请求POST

     NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

             // 在此位置生成一个要上传的数据体

             // form对应的是html文件中的表单

 

 

             UIImage *image = [UIImage imageNamed:@"头像1"];

             NSData *data = UIImagePNGRepresentation(image);

 

             // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名

             // 要解决此问题,

             // 可以在上传时使用当前的系统事件作为文件名

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

             // 设置时间格式

             formatter.dateFormat = @"yyyyMMddHHmmss";

             NSString *str = [formatter stringFromDate:[NSDate date]];

             NSString *fileName = [NSString stringWithFormat:@"%@.png", str];

 

 

 

          此方法参数

          1. 要上传的[二进制数据]

          2. 对应网站上[upload.php]处理文件的[字段"file"]

          3. 要保存在服务器上的[文件名]

          4. 上传文件的[mimeType]

 

             [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];

         }];


     // 3. operation包装的urlconnetion

     AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];


     [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    45         NSLog(@"上传完成");

    46     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        47         NSLog(@"上传失败->%@", error);

        48     }];

 

     //执行

     [_httpClient.operationQueue addOperation:op];

*/


@end



NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/user/uploadCustomFile.do" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { 
        [formData appendPartWithFileData:imageDatass name:strTime fileName:strPath mimeType:@"image/png"]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation allocinitWithRequest:request]; 
    [operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { 
    }]; 
       [operation start]; 
 
 
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
     { 
         NSLog(@"成功呢!json ===%@",operation.responseString); 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
         NSLog(@"Failure: %@", error); 
     }]; 
} 


ios 使用UIImagePickerController 打开图片库和相机选择图片界面为英文描述,修改为简体中文的方法:


在info.plist中添加Localizations设置item为Chinese (simplified)。

这样打开图片库或拍照的时候就可以显示简体中文了





0 0