进入相册选取图片和拍照方法 和解决在横屏状态下的调试

打开相册或者打开相机,选取照片或拍照这种功能很常见,之前也做过,这次公司做的一个ipad项目要求支持横屏状态,但是在横屏状态下进入相册程序会闪退,后来才知道,进入相册默认是不支持返回竖屏,这样在横屏状态下时进入就会程序退出,下面是我的解决办法

在选取进入相册时标记状态,这里我使用单例传值的方式,在横屏状态时我标记为1 当单例值为1的时候返回为横屏 在 Appdelegate.m中

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if ([DataHelp shareData].isLeft == 1) {
        [DataHelp shareData].isLeft = 0;
        return UIInterfaceOrientationMaskAll;
    }else
    {
        return UIInterfaceOrientationMaskLandscape;
    }
}

选择进入还是摄像机的提示框

//加载提示框
- (void)actionSheet
{
    if([[[UIDevice
          currentDevice] systemVersion] floatValue]>=8.0) {
   self.modalPresentationStyle=UIModalPresentationOverCurrentContext; //这个地方ios8以后要用UIModalPresentationOverCurrentContext否则打开时打印报警告(有强迫症,看到警告比报错还烦)
        actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:Localized(@"取消") destructiveButtonTitle:nil otherButtonTitles:Localized(@"打开相机"),Localized(@"从手机相册获取"),Localized(@"取消"),nil];
        actionSheet.backgroundColor = ScrollerColor;
        [actionSheet showInView:_CamearView.view];
    }
}
//  提示框的点击事件
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
        switch (buttonIndex) {
        case 0:
                [_BacView removeFromSuperview];
                [self performSelector:@selector(takePhoto) withObject:nil afterDelay:0.3];
            break;
            case 1:
                 [_BacView removeFromSuperview];
                [DataHelp shareData].isLeft = 1;

                [self performSelector:@selector(LocaPhoto) withObject:nil afterDelay:0.3];
            break;

            case 2:
                 [_BacView removeFromSuperview];
        default:
            break;
    }
}

//点击的执行事件

- (void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
        picker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
//        BaseViewController *bace = [BaseViewController new];
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {

    }
}

- (void)LocaPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
//    BaseViewController *bace = [BaseViewController new];
    [self presentViewController:picker animated:YES completion:nil];
}

选择图片或者拍照完成后点击确定的执行代码如下

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {

        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        //图片压缩一半
         [self compressImage:image toTargetWidth:0.5];

        //先把图片转成NSData
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 0.5); //后面的参数是压缩比例 
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];

            //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];

            //得到选择后沙盒中图片的完整路径
        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,@"/image.png"];

        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];

        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
//        
        NSData *ImageDaraArray = [[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"%@CellImageData",UserNameString]];
        NSMutableArray *mutAtrray = [NSKeyedUnarchiver unarchiveObjectWithData:ImageDaraArray];
        for (int i = 0; i < mutAtrray.count; i++) {
            [_CellMutArray replaceObjectAtIndex:i withObject:mutAtrray[i]];
        }
//        _CellMutArray = [mutAtrray mutableCopy];
        [_CellMutArray replaceObjectAtIndex:_CellIndex withObject:image];
        NSData *IMageData;
        IMageData = [NSKeyedArchiver archivedDataWithRootObject:_CellMutArray];
        [[NSUserDefaults standardUserDefaults]setObject:IMageData forKey:[NSString stringWithFormat:@"%@CellImageData",UserNameString]];
        [_table reloadData];
    }
}

以上是选取相册图片,或摄像机拍照 在横屏状态下程序报错解解决方法

2.第二种方法

在stackflow上还看到使用category 继承UIImagePickerController 来解决横屏状态下的但是我试了没有解决问题,我也将方法贴出来,希望有看到的看看是什么原因导致失败

首先Command+N建立一个延展继承自UIImagePickerController
UIImagePickerController+PickerImage.h

#import <UIKit/UIKit.h>

@interface UIImagePickerController (PickerImage)
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
- (BOOL)shouldAutorotate;
- (NSUInteger) supportedInterfaceOrientations;


UIImagePickerController+PickerImage.m


#import "UIImagePickerController+PickerImage.h"

@implementation UIImagePickerController (PickerImage)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return UIInterfaceOrientationIsLandscape( interfaceOrientation );
}
-(BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger) supportedInterfaceOrientations{
#ifdef __IPHONE_6_0
    return UIInterfaceOrientationMaskAllButUpsideDown;
    //return UIInterfaceOrientationMaskLandscape;
#endif
}
@end

在选取操作的控制器中加入下面的方法

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

补充一个图片压缩的问题

- (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;
}

希望有遇到同样问题的指点;

为了在Android Studio中实现拍照和从相册选取图片的功能,您需要执行以下操作: 1.添加以下权限到AndroidManifest.xml文件中: <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-feature android:name="android.hardware.camera"/> 2.在主要活动(Main Activity)中添加以下代码来调用相机并拍照: private static final int CAMERA_REQUEST = 1888; private Button button; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); imageView = (ImageView)findViewById(R.id.imageView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) { Bitmap photo = (Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(photo); } } 3.在主要活动中添加以下代码来调用相册选取图片: private static final int PICK_IMAGE_REQUEST = 1; private Button button1; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button) findViewById(R.id.button1); imageView = (ImageView)findViewById(R.id.imageView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); } } 确保您在AndroidManifest.xml文件中添加了必要的权限,并按照上述代码操作,就可以实现在Android Studio中拍照和从相册选取图片的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值