`
810364804
  • 浏览: 779787 次
文章分类
社区版块
存档分类
最新评论

通过相机相册获取图片

 
阅读更多

在很多android应用中需要通过手机获取图片,最方便最有效的方式就是利用系统相机相册或者手机中已经存在的能够获取图片的应用来获取了,当然你也可以自己利用硬件设备,通过android系统提供的API来开发一个属于自己的功能模块来捕获图片,但大多数情况下并不需要我们去开发这样的一个功能模块,也没有必要。下面是通过系统的相机相册获取图片的例子:

第一步:创建激活系统相机相册的意图。

private void dispatchFromAlbumIntent(int actionCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);  
		startActivityForResult(intent, actionCode);
	}

	private void dispatchTakePictureIntent(int actionCode) {
		
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		fileUri = Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE));
		takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 
		startActivityForResult(takePictureIntent, actionCode);
		
	}

第二步:获取返回的数据。

重写Activity中的onActivityResult()方法,在里面获取返回的数据,并对数据做相应的处理。

@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		//fetch a picture from camera
		if (requestCode == CAMERA_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				galleryAddPic();

				Log.i("hello", "fileUri:"+fileUri.toString());
				Bitmap bitmap = decodeSampledBitmapFromFile(fileUri.getPath(), 100, 100);
				mImageView.setImageBitmap(bitmap);
			} else if (resultCode == RESULT_CANCELED) {
				// User cancelled the image capture
			} else {
				// Image capture failed, advise user
			}
		}
		
		//fetch a picture from album
		if (requestCode == ALBUM_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				Uri selectedImage = data.getData();
	            String[] filePathColumn = {MediaStore.Images.Media.DATA};

	            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	            cursor.moveToFirst();

	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String filePath = cursor.getString(columnIndex);
	            cursor.close();
	            
	            File file = new File(filePath);
	            fileUri = Uri.fromFile(file);
	            Log.i("hello", "fileUri--"+fileUri.toString());
	            Log.i("hello", "selectedImage--"+selectedImage.toString());
	            
	            Bitmap bitmap = decodeSampledBitmapFromFile(filePath, 100, 100);
	            mImageView.setImageBitmap(bitmap);
			} else if (resultCode == RESULT_CANCELED) {
				// User cancelled the image capture
			} else {
				// Image capture failed, advise user
			}
		}
	}

里面用到的工具方法:

/** Create a File for saving an image or video */
	public File getOutputMediaFile(int type) {

		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"MyCameraApp");

		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			mediaStorageDir.mkdirs();
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			Log.i("hello", "mediaFile.getName()------" + mediaFile.getName());
		} else {
			return null;
		}
		return mediaFile;
	}


public static Bitmap decodeSampledBitmapFromFile(String pathName, int reqWidth, int reqHeight){
		// First decode with inJustDecodeBounds=true to check dimensions
	    final BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(pathName, options);
	    // Decode bitmap with inSampleSize set
	    options.inJustDecodeBounds = false;
	    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
	    options.inPurgeable = true;
	    
	    Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);
	    return bitmap;
	}
	
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics