该功能主要实现上传图片到服务器,选择图片的方式有两种,一种是从手机相册中选择,另一种是调用手机摄像头拍照。如图:
Java 代码
复制内容到剪贴板
- /*用来标识请求照相功能的activity*/
- private static final int CAMERA_WITH_DATA = 1001;
- /*用来标识请求gallery的activity*/
- private static final int PHOTO_PICKED_WITH_DATA = 1002;
Java 代码
复制内容到剪贴板
- private Bitmap bitMap; //用来保存图片
- private boolean hasImage; //是否已经选择了图片
Java 代码
复制内容到剪贴板
- /**
- * 拍照获取图片
- *
- */
- protected void doTakePhoto() {
- try {
- Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- startActivityForResult(cameraIntent, CAMERA_WITH_DATA);
- } catch (ActivityNotFoundException e) {
- e.printStackTrace();
- }
- }
- /**
- * 从本地手机中选择图片
- */
- private void doSelectImageFromLoacal(){
- Intent localIntent = new Intent();
- localIntent.setType("image/*");
- localIntent.setAction("android.intent.action.GET_CONTENT");
- Intent localIntent2 = Intent.createChooser(localIntent, "选择图片");
- startActivityForResult(localIntent2, PHOTO_PICKED_WITH_DATA);
- }
然后需要重写onActivityResult()方法,判断是否那种方式获取的图片。
Java 代码
复制内容到剪贴板
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (resultCode != RESULT_OK)
- return;
- switch (requestCode) {
- case PHOTO_PICKED_WITH_DATA: //从本地选择图片
- if (bitMap != null && !bitMap.isRecycled()) {
- bitMap.recycle();
- }
- Uri selectedImageUri = data.getData();
- if(selectedImageUri != null){
- try {
- bitMap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImageUri));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- //下面这两句是对图片按照一定的比例缩放,这样就可以完美地显示出来。有关图片的处理将重新写文章来介绍。
- int scale = ImageThumbnail.reckonThumbnail(bitMap.getWidth(), bitMap.getHeight(), 500, 600);
- bitMap = ImageThumbnail.PicZoom(bitMap, (int) (bitMap.getWidth() / scale), (int) (bitMap.getHeight() / scale));
- imageView.setImageBitmap(bitMap);
- imageView.setVisibility(View.VISIBLE);
- hasImage = true;
- }
- break;
- case CAMERA_WITH_DATA: //拍照
- Bundle bundle = data.getExtras();
- bitMap = (Bitmap)bundle.get("data");
- if (bitMap != null)
- bitMap.recycle();
- bitMap = (Bitmap) data.getExtras().get("data");
- int scale = ImageThumbnail.reckonThumbnail(bitMap.getWidth(), bitMap.getHeight(), 500, 600);
- bitMap = ImageThumbnail.PicZoom(bitMap, (int) (bitMap.getWidth() / scale), (int) (bitMap.getHeight() / scale));
- imageView.setImageBitmap(bitMap);
- imageView.setVisibility(View.VISIBLE);
- hasImage = true;
- break;
- }
- }
-