Android调用系统相机相册,可选择性裁剪

相机相册的代码网上一大堆,大部分会有兼容性问题,找了一个相对稳定的,不过也是拼凑的,分享下,有问题还请大家完善下:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.Toast;

public class BaseActivity extends Activity {

	public static final int REQUEST_CODE_CAMERA = 2001;
	public static final int REQUEST_CODE_LOCAL = 2002;
	public static final int CROP_CODE = 2003;
	// 设置成你想要放在的地方,存放临时图片***********
	public static String myImagePath = "/sdcard/";
	// 选择后的file,可用于网络传输
	public File imgFile;
	// 是否裁剪
	private boolean isCrop = true;
	// 拍照用的file
	private File cameraFile;
	// 显示控件
	private ImageView img;

	// 拍照(我是写在BaseActivity里面,所以需要传递一个ImageView)
	public void pickPicture(ImageView img) {
		this.img = img;
		if (!isExitsSdcard()) {
			Toast.makeText(getApplicationContext(), "SD卡不存在,不能拍照", 0).show();
			return;
		}

		cameraFile = new File(myImagePath, System.currentTimeMillis() + ".jpg");
		cameraFile.getParentFile().mkdirs();
		startActivityForResult(
				new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
						MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
				REQUEST_CODE_CAMERA);
	}

	// 选择相册
	public void takePicture(ImageView img) {
		this.img = img;
		Intent intent;
		if (Build.VERSION.SDK_INT < 19) {
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
		} else {
			intent = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		}
		startActivityForResult(intent, REQUEST_CODE_LOCAL);
	}

	// 回调
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
			if (data != null) {
				Uri uri = data.getData();
				if (uri != null) {
					if (isCrop) {
						cropImage(uri);
					} else {
						String filePath = null;
						if ("content".equalsIgnoreCase(uri.getScheme())) {
							String[] projection = { "_data" };
							Cursor cursor = null;

							try {
								cursor = getContentResolver().query(uri,
										projection, null, null, null);
								int column_index = cursor
										.getColumnIndexOrThrow("_data");
								if (cursor.moveToFirst()) {
									filePath = cursor.getString(column_index);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else if ("file".equalsIgnoreCase(uri.getScheme())) {
							filePath = uri.getPath();
						}
						imgFile = new File(filePath);
						if (imgFile == null || !imgFile.exists()) {
							Toast.makeText(getApplicationContext(), "文件不存在", 0)
									.show();
							return;
						}
						if (img != null) {
							Bitmap bitmap = getLoacalBitmap(filePath);
							img.setImageBitmap(bitmap);
						}
					}
				}
			}
		}
		if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
			if (cameraFile != null && cameraFile.exists()) {
				String filePath = cameraFile.getAbsolutePath();
				imgFile = new File(filePath);
				if (imgFile == null || !imgFile.exists()) {
					Toast.makeText(getApplicationContext(), "文件不存在", 0).show();
					return;
				}
				if (isCrop) {
					cropImage(Uri.fromFile(imgFile));
				} else {
					Bitmap bitmap = getLoacalBitmap(filePath);
					if (img != null) {
						img.setImageBitmap(bitmap);

					}
				}
			}
		}

		if (CROP_CODE == requestCode) {
			if (resultCode == RESULT_OK) {
				// 拿到剪切数据
				Bitmap bmap = data.getParcelableExtra("data");

				// 显示剪切的图像
				if (img != null) {
					img.setImageBitmap(bmap);
				}
				String filePath = myImagePath + System.currentTimeMillis()
						+ ".jpg";
				cpAssets(bmap, filePath);
				imgFile = new File(filePath);
			}
		}
	}

	//-------------以下代码可以考虑放在方法类里面---------------------------
	
	/**
	 * 加载本地图片
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public void cropImage(Uri mUri) {
		if (null == mUri)
			return;
		Intent intent = new Intent();

		intent.setAction("com.android.camera.action.CROP");
		intent.setDataAndType(mUri, "image/*");// mUri是已经选择的图片Uri
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);// 输出图片大小 (可自行设置大小)
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, CROP_CODE);
	}

	/**
	 * 检测Sdcard是否存在
	 * 
	 * @return
	 */
	public static boolean isExitsSdcard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			return true;
		else
			return false;
	}

	/**
	 * 拷贝资源到data
	 * 
	 * @param inputStream
	 * @param path
	 */
	public static void cpAssets(Bitmap bitmap, String path) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
			baos.toByteArray();
			RandomAccessFile ok = new RandomAccessFile(createFile(path), "rw");
			byte[] b = baos.toByteArray();
			ok.write(b);
			ok.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过提供的文件名在默认路径下生成文件
	 * 
	 * @param fileName
	 *            文件的名称
	 * @return 生成的文件
	 */
	public static File createFile(String fileName) {
		File file = new File(fileName);
		if (!isFileExist(file)) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// LogX.trace(e.getMessage(), " fail");
				if (fileName.lastIndexOf("/") > -1) {
					String fatherRoot = fileName.substring(0,
							fileName.lastIndexOf("/"));
					File filetemp = new File(fatherRoot);
					filetemp.mkdirs();
					try {
						file.createNewFile();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
		return file;
	}

	/**
	 * 是否存在此文件
	 * 
	 * @param file
	 *            判断是否存在的文件
	 * @return 存在返回true,否则返回false
	 */
	public static boolean isFileExist(final File file) {
		boolean isExist = false;
		// 在无SD卡时file会为空
		if (file == null) {
			return false;
		}
		if (file.exists()) {
			isExist = true;
		} else {
			isExist = false;
		}
		return isExist;
	}

}

有可能会报一些权限的错误,加上就可以了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值