首页 > 代码库 > Android拍照,剪切,并放入SD卡

Android拍照,剪切,并放入SD卡

android拍照之后,先对图片进行一次剪切,最后将图片保存到指定的目录。在项目需要用户拍照,并对图片进行剪切后,发送到服务器端做验证。这里贴出来一个小例子,能够实现基本的功能。文章最后会给出来demo。界面上就是一个点击事件。

1.首先点击事件中启动拍照,这里写死了图片的名称。实际上可以通过在公用的类中定义一个静态变量来操作。

public void tackPhoto() {
	String status = Environment.getExternalStorageState();
	if (status.equals(Environment.MEDIA_MOUNTED)) {
		try {
			File filePath = Environment.getExternalStorageDirectory();
			Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				File f = new File(filePath, "test.jpg");
				Uri u = Uri.fromFile(f);
				intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
				startActivityForResult(intent, FLAG_CHOOSE_PHONE);
			} catch (ActivityNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
2.在onActivityResult方法中获得值
@Override
       protected void onActivityResult (int requestCode, int resultCode, Intent data) {
             if (resultCode == RESULT_OK) {
                  File filePath = Environment.getExternalStorageDirectory();
                  File f = new File(filePath, "test.jpg");
                   if (requestCode == FLAG_CHOOSE_PHONE) {
                        Toast. makeText( this, "FLAG_CHOOSE_PHONE", Toast.LENGTH_SHORT )
                                    .show();
                        String path = f.getAbsolutePath();
                        Intent intent = new Intent();
                        intent.setAction( "com.android.camera.action.CROP" );
                        intent.setDataAndType(Uri. fromFile( newFile(path)), "image/*" );// mUri是已经选择的图片 Uri
                        intent.putExtra( "crop", "true");
                        intent.putExtra( "aspectX", 3); // 裁剪框比例
                        intent.putExtra( "aspectY", 3);
                        intent.putExtra( "outputX", 150); // 输出图片大小
                        intent.putExtra( "outputY", 150);
                        intent.putExtra( "return-data", true);
                        startActivityForResult(intent,FLAG_CROP_PHONE);
                  } else if (requestCode == FLAG_CROP_PHONE) {
                        Bitmap bmap = data.getParcelableExtra( "data");
                         if (bmap != null) {
                               try {
                                    bmap.compress(Bitmap.CompressFormat. JPEG, 0,
                                                 newFileOutputStream(f));
                              } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                              }
                        }
                  }
            }
      }
3.最后要添加一些权限
< uses-permission android:name = "android.permission.CAMERA" />
<uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" />
下载地址: http://www.oschina.net/action/code/download?code=44069&id=61639

Android拍照,剪切,并放入SD卡