android 照相或选择图片最新整理,处理2.1SDK兼容问题。

经过最近项目历练不同手机型号已经SDK版本以后,发现上次写的名为:android2.3选择相册图片或者调用系统照相 的文章中,存在一个bug,就是在2.1的索尼手机上使用不了,并且无法获取到图片原生大小。下面做下最近的测试成功的记录,主要以调用相册和,系统摄像机为主:

	/**
	 * Show Check Image Dialog
	 */
	private void showheckImageDialog() {
		final CharSequence[] items = { getResources().getString(R.string.photo_manager_check_cameras),
				getResources().getString(R.string.photo_manager_check_image) };
		Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.photo_manager_check_dialog_title).setItems(items, this);
		builder.create().show();
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (which == 0) { // Cameras
			try {
				// get image file save path
				temporaryPhotoPath = getImageFilePath();

				// user sdk cameras
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				File captureFile = new File(temporaryPhotoPath);
				this.captureUri = Uri.fromFile(captureFile);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri);
				startActivityForResult(intent, CAMERAMAN_IMAGE);
			} catch (Exception e) {
				Logging.e("error", e.getMessage());
			}
		} else {
			Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/*");
			startActivityForResult(Intent.createChooser(getImage, getString(R.string.photo_select_title)), SELECT_IMAGE);
		}
	}

说明一下,上面 temporaryPhotoPath 是图片需要保存的路径。

下面是回调方法获取图片路径的方法,需要注意一下的是 不能用回调方法的 Intent 参数获取image,因为这样获取的是被系统缩小的图片对象,而不是图片的原生图像。

@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Bitmap bitmap = null;
		String parth = null;
		if (data != null) {
			// get file path
			parth = FileManager.getImagePathByIntent(this, data);
		}
		// copy file
		if (StringUtil.isExistsData(parth) && !parth.equals(this.temporaryPhotoPath)) {
			// get file save path
			if (!StringUtil.isExistsData(this.temporaryPhotoPath)) {
				this.temporaryPhotoPath = getImageFilePath();
			}
			FileManager.copyFile(parth, this.temporaryPhotoPath);
		}
		// get image
		if (StringUtil.isExistsData(temporaryPhotoPath)) {
			bitmap = FileManager.converntBitmapSize(temporaryPhotoPath, 960);
			this.temporaryPhotoPath = null;
		}

上面的代码中copyFile ()是将图片复制到我们指定的目录, 下面是获取图片的路径的方法和复制文件的方法:

	/**
	 * Get Image By Intent
	 * 
	 * @param data
	 * @return
	 */
	public static String getImagePathByIntent(Activity activity, Intent data) {
		String path = null;
		Cursor cursor = null;
		try {
			Uri originalUri = data.getData();
			path = originalUri.toString();
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = activity.managedQuery(originalUri, proj, null, null, null);
			if (cursor != null) {
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				path = cursor.getString(column_index);
			}
			path = path.substring(path.indexOf("/sdcard"), path.length());
		} catch (Exception e) {
			Logging.e("getImageByIntent error", e.getMessage());
		} finally {
			if (cursor != null) cursor.close();
		}
		return path;
	}

/**
	 * copy file
	 * 
	 * @param sourcePath
	 * @param newPath
	 * @return
	 */
	public static boolean copyFile(String sourcePath, String newPath) {
		boolean isSuccess = false;
		try {
			File sourceFile = new File(sourcePath);
			if (!sourceFile.exists()) {
				return isSuccess;
			}
			// delete already file
			File newFile = new File(newPath);
			if (newFile.exists()) {
				newFile.delete();
			}

			// copy file
			isSuccess = sourceFile.renameTo(newFile);
		} catch (Exception e) {
			Logging.e("copyFile error", e.getMessage());
		}
		return isSuccess;
	}

下面是转换图片大小并保存的方法:

/**
	 * convert image size
	 * 
	 * @param imagePath
	 *            String image file path
	 * @param width
	 *            Int new image max width
	 * @param height
	 *            Int new image max height
	 * @return
	 */
	public static Bitmap converntBitmapSize(String imagePath, int maxSize) {
		Bitmap bitmap = null;
		int defaultMaxSize = 960;
		try {
			if (maxSize > 0) {
				defaultMaxSize = maxSize;
			}
			File imageFile = new File(imagePath);
			if (imageFile.exists()) {
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(imagePath, options);

				// the resource image max size
				int sourceMaxSize = Math.max(options.outWidth, options.outHeight);

				if (sourceMaxSize < 1) {
					return null;
				}

				int scale = sourceMaxSize / defaultMaxSize;

				options.inJustDecodeBounds = false;
				options.inSampleSize = scale;
				// first narrow image
				bitmap = BitmapFactory.decodeFile(imagePath, options);

				int newMaxSize = Math.max(bitmap.getWidth(), bitmap.getHeight());

				if (newMaxSize > defaultMaxSize) {
					// second narrow image
					float newSize = (float) defaultMaxSize / (float) newMaxSize;
					Matrix matrix = new Matrix();
					matrix.postScale(newSize, newSize);
					bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
					matrix = null;
				}
				saveImage(bitmap, imagePath);
			}
		} catch (Exception e) {
			Logging.e("converntBitmapSize", e.getMessage());
		}
		return bitmap;
	}

经过测试,目前没有遇到无法使用的情况。



你可能感兴趣的:(android,exception,image,String,File,Matrix)