Android 拍照/相册 选择图片工具

一个集成拍照和从相册选择图片的工具,集成为Activtiy,注册时修改下该Activity的Theme;

调用方式:


1,如果要将获取的图片进行剪切  :

  

<span style="font-size:14px;"> Intent intentPhoto = new Intent(UserInfoActivity.this,CropImage.class);
    intentPhoto.putExtra(CropImage.outputX, outputw);
    intentPhoto.putExtra(CropImage.outputY, outputh);
    intentPhoto.putExtra(CropImage.aspectX, 1);
    intentPhoto.putExtra(CropImage.aspectY, 1);
    intentPhoto.putExtra("ifTailorFlag", true);// 标志位是否启动裁剪
    this.startActivityForResult(intentPhoto, requestCode);</span>



2,如果不需要剪切:将剪切标志位设置为false即可。

  

<span style="font-size:14px;"> Intent intentPhoto = new Intent(UserInfoActivity.this,CropImage.class);
    intentPhoto.putExtra(CropImage.outputX, outputw);
    intentPhoto.putExtra(CropImage.outputY, outputh);
    intentPhoto.putExtra(CropImage.aspectX, 1);
    intentPhoto.putExtra(CropImage.aspectY, 1);
    intentPhoto.putExtra("ifTailorFlag", false);// 标志位是否启动裁剪
    this.startActivityForResult(intentPhoto, requestCode);</span>



获取选择的结果:

在启动的activity中覆写activity的这个方法;

<span style="font-size:14px;">@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == requestCode) {
                       //1,判断是否有 图片信息返回
                Boolean have_image = data.getBooleanExtra(CropImage.have_image,
                         false);

                        //2,有拿到图片信息

               if (have_image) {

                     // 3,取出图片
                  String  mImagePath = data.getStringExtra(CropImage.image_path);
                    // 4,将图片显示出来

                    Bitmap bm = CropImage.optimizeBitmap(mImagePath,
                            AppContext.metrics.widthPixels / 3,
                            AppContext.metrics.widthPixels / 3);
                    iv_avatar.setImageBitmap(bm);

                }

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }</span>


最后贴上CropImage.java代码

<span style="font-size:14px;">public class CropImage extends Activity {
	public static final String have_image = "result";
	public static final String image_path = "image_path";

	public static final String aspectX = "aspectX";
	public static final String aspectY = "aspectY";
	public static final String outputX = "outputX";
	public static final String outputY = "outputY";

	private static final int NONE = 0;
	private static final int PHOTO_GRAPH = 1;// 拍照
	private static final int PHOTO_ZOOM = 2; // 缩放
	private static final int PHOTO_RESOULT = 3;// 结果
	private static final String IMAGE_UNSPECIFIED = "image/*";

	private int aspX = 0;
	private int aspY = 0;
	private int outX = 100;
	private int outY = 100;

	private String photoPath = Environment.getExternalStorageDirectory()
			.getPath() + "/demo/";
	private String imagePath = Environment.getExternalStorageDirectory()
			.getPath() + "/demo/image/";
	private String tempimage = null;
	private String imageurl = null;
	private boolean ifTailorFlag = true;// 是否启动裁剪,默认启动

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("");

		try {
			// 创建保存路径
			isFolderExists(photoPath);
			if (isFolderExists(imagePath)) {
				try {
					new File(imagePath, ".nomedia").createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			Intent i = getIntent();
			Bundle bundle = i.getExtras();
			if (bundle != null) {
				ifTailorFlag = bundle.getBoolean("ifTailorFlag");
			}

			aspX = i.getIntExtra(aspectX, 0);
			if (aspX == 0) {
				aspX = Integer.valueOf(i.getStringExtra(aspectX));
			}
			aspY = i.getIntExtra(aspectY, 0);
			if (aspY == 0) {
				aspY = Integer.valueOf(i.getStringExtra(aspectY));
			}
			outX = i.getIntExtra(outputX, 0);
			if (outX == 0) {
				outX = Integer.valueOf(i.getStringExtra(outputX));
			}
			outY = i.getIntExtra(outputY, 0);
			if (outY == 0) {
				outY = Integer.valueOf(i.getStringExtra(outputY));
			}

			// 判断是否传入值。未传入则直接返回
			if (aspX != 0 && aspY != 0 && outX != 0 && outY != 0) {
				showPicSelectDialog();
			} else {
				result(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * 打开选择图片对话框
	 */
	private void showPicSelectDialog() {
		AlertDialog.Builder builder = new Builder(this);
		View view = View.inflate(this, R.layout.dialog_select_pic, null);
		TextView tv_album = (TextView) view.findViewById(R.id.tv_album);
		TextView tv_camera = (TextView) view.findViewById(R.id.tv_camera);
		final AlertDialog dialog = builder.setView(view).create();
		dialog.show();
		tv_camera.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				// 打开相机
				tempimage = getRandomString(7)
						+ ".jpg";
				Intent intent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra("return-data",
						false);
				intent.putExtra(
						MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(
								photoPath,
								tempimage)));
				startActivityForResult(intent,
						PHOTO_GRAPH);
			}
		});
		tv_album.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				// 打开图库
				Intent intent = new Intent(
						Intent.ACTION_PICK, null);
				intent.putExtra("return-data",
						false);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						IMAGE_UNSPECIFIED);
				startActivityForResult(intent,
						PHOTO_ZOOM);
			}
		});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			if (resultCode == Activity.RESULT_CANCELED) {
				try {
					result(null);
					CropImage.this.finish();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			if (resultCode == Activity.RESULT_OK) {
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
					Log.i("TestFile",
							"SD card is not avaiable/writable right now");
					return;
				} else if (resultCode == NONE) {
					try {
						result(null);
						CropImage.this.finish();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (requestCode == PHOTO_GRAPH) {// 拍照
					File picture = new File(photoPath + tempimage);// 设置文件保存路径
					try {
						startPhotoZoom(Uri.fromFile(picture));
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (requestCode == PHOTO_ZOOM) {// 读取相册缩放图片
					Uri uri = data.getData();
					if (uri != null && uri.toString().contains("content://")) {
						ContentResolver cr = this.getContentResolver();
						Cursor cursor = cr.query(uri, null, null, null, null);
						if (cursor != null) {
							cursor.moveToFirst();
							startPhotoZoom(Uri.fromFile(new File(cursor
									.getString(1))));
						}
				
					} else {
						try {
							startPhotoZoom(data.getData());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else if (requestCode == PHOTO_RESOULT) { // 处理结果
					result(imageurl);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void startPhotoZoom(Uri uri) {
		imageurl = imagePath + getRandomString(7) + ".jpg";

		try {// 压缩图片
			File file = new File(uri.getPath());
			if (file.exists()) {// 图片大于1M就压缩
				if (file.length() > 1024 * 1024) {
					Bitmap bitmap = optimizeBitmap(uri.getPath(),
							AppContext.metrics.widthPixels,
							AppContext.metrics.heightPixels);
					OutputStream os = new FileOutputStream(uri.getPath());
					bitmap.compress(CompressFormat.JPEG, 80, os);
					os.flush();
					os.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (ifTailorFlag) {// 如果有启动裁剪
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "false");
			intent.putExtra("aspectX", aspX);
			intent.putExtra("aspectY", aspY);
			intent.putExtra("outputX", outX);
			intent.putExtra("outputY", outY);
			intent.putExtra("scale", true);
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(imageurl)));
			intent.putExtra("return-data", false);
			intent.putExtra("outputFormat",
					Bitmap.CompressFormat.JPEG.toString());
			intent.putExtra("noFaceDetection", true); // no face detection
			startActivityForResult(intent, PHOTO_RESOULT);
		} else {// 如果没有启动裁剪:没有启动裁剪直接压缩图片并返回
			result(uri.getPath());
		}
	}

	public static Bitmap optimizeBitmap(String pathName, int maxWidth,
			int maxHeight) {
		Bitmap result = null;
		try {
			// 图片配置对象,该对象可以配置图片加载的像素获取个数
			BitmapFactory.Options options = new BitmapFactory.Options();
			// 表示加载图像的原始宽高
			options.inJustDecodeBounds = true;
			result = BitmapFactory.decodeFile(pathName, options);
			// Math.ceil表示获取与它最近的整数(向上取值 如:4.1->5 4.9->5)
			int widthRatio = (int) Math.ceil(options.outWidth / maxWidth);
			int heightRatio = (int) Math.ceil(options.outHeight / maxHeight);
			// 设置最终加载的像素比例,表示最终显示的像素个数为总个数的
			if (widthRatio > 1 || heightRatio > 1) {
				if (widthRatio > heightRatio) {
					options.inSampleSize = widthRatio;
				} else {
					options.inSampleSize = heightRatio;
				}
			}
			// 解码像素的模式,在该模式下可以直接按照option的配置取出像素点
			options.inPreferredConfig = Config.RGB_565;
			options.inJustDecodeBounds = false;
			result = BitmapFactory.decodeFile(pathName, options);

		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return result;
	}

	boolean isFolderExists(String strFolder) {
		File file = new File(strFolder);
		if (!file.exists()) {
			if (file.mkdirs()) {
				return true;
			} else {
				return false;
			}
		}
		return true;
	}

	@SuppressLint("NewApi")
	public void result(String image_path) {
		try {
			Intent i = new Intent();
			if (null != image_path && !"".equals(image_path)) {
				i.putExtra(have_image, true);
				i.putExtra(this.image_path, image_path);
				
			} else {
				i.putExtra(have_image, false);
			}
			this.setResult(RESULT_OK, i);
			finish();
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			result("");
			CropImage.this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onConfigurationChanged(Configuration config) {
		super.onConfigurationChanged(config);
	}

	public static String getRandomString(int length) { // length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz0123456789"; // 生成字符串从此序列中取
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
}
</span>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值