iOS 调用相册/相机/图片压缩

  调用相机/相册的方法其实很简单,直接上代码。

  UIActionSheet *sheet;//先定义一个Actiongsheeet
if ( [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {//判断相机是否可用
sheet = [[UIActionSheet alloc] initWithTitle:@"Please choose!" delegate:self cancelButtonTitle:@"Cancle" destructiveButtonTitle:nil otherButtonTitles:@"Photo Album",@"Camera", nil];
}else{
sheet = [[UIActionSheet alloc] initWithTitle:@"Please choose" delegate:self cancelButtonTitle:@"Cancle" destructiveButtonTitle:nil otherButtonTitles:@"Photo Album", nil];
}
sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[sheet showInView:self.view];

-  (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *pick = [[UIImagePickerController alloc] init];
    pick.delegate = self;//设置代理,前面要遵守UINavigationControllerDelegate, UIImagePickerControllerDelegate两个协议
    if (buttonIndex == 0) {
        pick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//resourceType决定是调出相机还是选择相册
        [self presentViewController:pick animated:YES completion:nil];
    }
    if (buttonIndex == 1) {
        if ([actionSheet.title isEqualToString:@"Please choose"]) {
            
        }else{
            pick.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pick animated:YES completion:nil];
        }
        
    }

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info//imagePickview的协议
{
    UIImage *img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];//这样就可以把图片取出来了,最后返回原页面,可以打印一下info
    //然后可以根据自己的需要决定是否需要压缩一下图片
    [self scleToSize:img size:CGSizeMake(100,100)];


    [picker dismissViewControllerAnimated:YES completion:nil];
}

<pre>- (UIImage *)scaleToSize:(UIImage *<span style="color:#000000;">)img size:(CGSize)size{ //图片压缩  </span><span style="color:#008000;">  </span>
<span style="color:#000000;">    UIGraphicsBeginImageContext(size);  //取得bitmap的context</span><span style="color:#008000;">    </span>
    [img drawInRect:CGRectMake(<span style="color:#800080;">0</span>,<span style="color:#800080;">0</span><span style="color:#000000;">, size.width, size.height)];//设置新图片的大小    </span><span style="color:#008000;">    </span>
    UIImage* scaledImage =<span style="color:#000000;">UIGraphicsGetImageFromCurrentImageContext(); //生成图片   </span><span style="color:#008000;">    </span>
<span style="color:#000000;">    UIGraphicsEndImageContext();   //结束编辑 </span><span style="color:#008000;">    </span>
    <span style="color:#0000ff;">return</span><span style="color:#000000;"> scaledImage;    //返回图片
} </span>



 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值