android 照相或从相册获取图片并裁剪

照相或从相册获取图片并裁剪

  在android应用中很多时候都要获取图片(例如获取用户的头像)就需要从用户手机上获取图片。可以直接照,也可以从用户SD卡上获取图片,但获取到的图片未必能达到要求。所以要对图片进行一个

裁剪才能达到要求。

  下面直接用个例子来说明怎么样来获取照相图片和相册中的图片并进行裁剪。

  对其中的一些东西进行解释:

1.

创建一个文件对象dir是文件保存的路径,name是文件的名称

 File sdcardTemple = new File(dir, name); 

2.

Intent intent = new Intent( "android.media.action.IMAGE_CAPTURE");

API对android.media.action.IMAGE_CAPTURE的解释是:

Standard Intent action that can be sent to have the camera application capture an image and return it

就是打开照相应用获取照相的得到的图片

3.程序的功能就是点击button后选择是照相还是从相册中获取图片,然后又结果的返回个Activity进行显示选择了哪张图片

 public class MainActivity extends Activity implements OnClickListener {

     private Button selectImageBtn;
private ImageView imageView; private File sdcardTempFile;
private AlertDialog dialog;
private int crop = 180; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectImageBtn = (Button) findViewById(R.id.selectImageBtn);
imageView = (ImageView) findViewById(R.id.imageView); selectImageBtn.setOnClickListener(this);
// /mnt/sdcard/是裁剪后图片保存的文件夹 如果是照相的照片是保存在/sdcard/dcim/Camera/中的
sdcardTempFile = new File("/mnt/sdcard/", "tmp_pic_"
+ SystemClock.currentThreadTimeMillis() + ".jpg");
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public void onClick(View v) {
if (v == selectImageBtn) {
if (dialog == null) {
dialog = new AlertDialog.Builder(this).setItems(
new String[] { "相机", "相册" },
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
if (which == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
intent.putExtra("output",
Uri.fromFile(sdcardTempFile));
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);// 裁剪框比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", crop);// 输出图片大小
intent.putExtra("outputY", crop);
startActivityForResult(intent, 101);
} else {
Intent intent = new Intent(
"android.intent.action.PICK");
intent.setDataAndType(
MediaStore.Images.Media.INTERNAL_CONTENT_URI,
"image/*");
intent.putExtra("output",
Uri.fromFile(sdcardTempFile));
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);// 裁剪框比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", crop);// 输出图片大小
intent.putExtra("outputY", crop);
startActivityForResult(intent, 100);
}
}
}).create();
}
if (!dialog.isShowing()) {
dialog.show();
}
}
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bmp = BitmapFactory.decodeFile(sdcardTempFile.getAbsolutePath());
System.out.println(sdcardTempFile.getAbsolutePath());
imageView.setImageBitmap(bmp); } }

源码下载地址:源码

上一篇:Dictionary,hashtable, stl:map有什么异同?


下一篇:ios中摄像头/相册获取图片,压缩图片,上传服务器方法总结