Android学习之图片(一)——从相机和相册取图

来源:互联网 发布:臭苋菜 知乎 编辑:程序博客网 时间:2024/05/21 11:29

这是基本技能了,只是温习一下

转载请注明出处
[我的博客]http://www.lostbug.com

  • 相机取图
    一般取原图(Save the Full-size Photo),缩略图用处不多
    首先先建个文件,以便写入照片,并保存路径,以方便后期使用
String mCurrentPhotoPath;private File createImageFile() throws IOException {    // Create an image file name    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());    String imageFileName = "JPEG_" + timeStamp + "_";    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);    File image = File.createTempFile(        imageFileName,  /* prefix */        ".jpg",         /* suffix */        storageDir      /* directory */    );    // Save a file: path for use with ACTION_VIEW intents    mCurrentPhotoPath = "file:" + image.getAbsolutePath();    return image;}

然后创建和调用Intent

static final int REQUEST_TAKE_PHOTO = 1;private void dispatchTakePictureIntent() {    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    // Ensure that there's a camera activity to handle the intent    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {        // Create the File where the photo should go        File photoFile = null;        try {            photoFile = createImageFile();        } catch (IOException ex) {            // Error occurred while creating the File            ...        }        // Continue only if the File was successfully created        if (photoFile != null) {            Uri photoURI = Uri.fromFile(photoFile);            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);        }    }}

然后在onActivityResult里引用文件路径获取图片就行了

  • 相册取图

创建 并调用Intent

 private static final int RESULT_ALBUM_IMAGE=2;Intent i = new Intent(                        Intent.ACTION_PICK,                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);                startActivityForResult(i, RESULT_ALBUM_IMAGE);

在onActivityResult里获取图片:

 if (requestCode == RESULT_ALBUM_IMAGE && resultCode == RESULT_OK                && data != null) {            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]);            final String picturePath = cursor.getString(columnIndex);            Log.d("PICTUREPATH", picturePath);            cursor.close();            Bitmap bitmap=BitmapFactory.decodeFile(picturePath);            mImageView.setImageBitmap(bitmap);  }

就是这样啦

0 0