灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2519回复:0

Android 图像系列: 图片的裁剪与相机调用

楼主#
更多 发布于:2012-11-10 14:23

  有时候我们需要的图片并不适合我们想要的大小, 那么我们就可以用到系统自带的图片裁剪功能, 把规定范围的图像给剪出来。
 
  贴上部分代码:
 
[javascript]
//调用图库
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra("crop", "true");    // crop=true 有这句才能出来最后的裁剪页面.
intent.putExtra("aspectX", 5);      // 这两项为裁剪框的比例.
intent.putExtra("aspectY", 4);
//输出地址
intent.putExtra("output", Uri.fromFile(new File("SDCard/1.jpg")
intent.putExtra("outputFormat", "JPEG");//返回格式                      
[javascript] view plaincopy
startActivityForResult(Intent.createChooser(intent, "选择图片"), 1);

 
[java]
//调用相机
Intent intent = new Intent(
    MediaStore.ACTION_IMAGE_CAPTURE, null);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
    "SDCard/1.jpg")));
startActivityForResult(intent, 2);

在调用了以上任意一种方法后, 系统会返回onActivityResult, 我们在这个方法中处理就可以了
 
[java]
    /**
     * 获取返回的相片
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == 0)
            return;
 
        if (requestCode == 2)//调用系统裁剪
        {
            File picture = new File(mPhotoCachePath[mSelectedPhoto]);      
                        startPhotoZoom(Uri.fromFile(picture));  
        } else if (requestCode == PHOTO_CODE)//得到裁剪后的图片
        {
            try
            {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap bitmap = BitmapFactory.decodeFile("SDCard/1.jpg", options);
 
                if (bitmap != null)//保存图片
                {
                    mCacheBitmap = bitmap;
 
                    FileOutputStream fos = null;
                    fos = new FileOutputStream(mPhotoCachePath[mSelectedPhoto]);
                    mCacheBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                }
 
                
            } catch (Exception e)
            {
                // TODO: handle exception
            }
        }
 
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    /**
     * 裁剪图片
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {      
        Intent intent = new Intent("com.android.camera.action.CROP");      
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
        intent.putExtra("aspectX", 5);// 这两项为裁剪框的比例.
        intent.putExtra("aspectY", 4);// x:y=1:2
        intent.putExtra("output", Uri.fromFile(new File(mPhotoCachePath[mSelectedPhoto])));
        intent.putExtra("outputFormat", "JPEG");//返回格式    
        startActivityForResult(intent, PHOTO_CODE);      
}  

喜欢0 评分0
游客

返回顶部