处理相机拍照后Bitmap和图片旋转问题

在调用系统相机,拍照并保存在sdcard上后,有些图片是旋转过的,如何将他们再转回来了,我做了如下操作:

1.首先看图片的属性到底是旋转了多少度

/**
	 * 读取图片属性:旋转的角度
	 * 
	 * @param path
	 *            图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("图片旋转了:" + degree + " 度");
		return degree;
	}

2.其次读取sdcard上的图片文件,然后动态设置缩放比例,再将旋转了的图片再转回来,最后输出图片覆盖原来的图片

BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;// 为true的情况下decodeFile并不分配空间,但可计算出原始图片的长度和宽度
		// 获取这个图片的宽和高
		bitmap = BitmapFactory.decodeFile(imagePath, options); // 此时返回bm为空
		options.inSampleSize = calculateInSampleSize(options, 150, 150);
		// 重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false
		options.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		//如果图片旋转了,就给他转回来
		if(degree!=0){
			bitmap = UtilTool.rotaingImageView(degree,bitmap);
		}
		FileOutputStream out;
		try {
			out = new FileOutputStream(new File(Constant.SDCARD_ROOT_PATH
					+ Constant.SAVE_PATH_IN_SDCARD + IMAGE_CAPTURE_NAME));
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

动态设置缩放比例

public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
		}
		return inSampleSize;
	}

图片旋转

public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}



你可能感兴趣的:(android)