参考 http://my.eoe.cn/isnull/archive/564.html
/** * 解决OOM问题 */ private Bitmap convertBitmap(File file) throws IOException { int degree = readPictureDegree(file.toString()); Bitmap bitmap = null; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream fis = new FileInputStream(file.getAbsolutePath()); BitmapFactory.decodeStream(fis, null, o); int width_tmp = o.outWidth, height_tmp = o.outHeight; o.inJustDecodeBounds = false; fis.close(); Log.v("图片宽度+图片高度", width_tmp + "+" + height_tmp); int scale = 1; float sw = (float) width_tmp / (float) 600; if (sw > 2) { scale = (int) Math.floor(sw); } o.inSampleSize = scale; fis = new FileInputStream(file.getAbsolutePath()); bitmap = BitmapFactory.decodeStream(fis, null, o); width_tmp = bitmap.getWidth(); height_tmp = bitmap.getHeight(); Log.v("图片宽度2+图片高度2", width_tmp + "+" + height_tmp); if (width_tmp > 600) { sw = (float) 600 / (float) width_tmp; bitmap = small(sw, width_tmp, height_tmp,degree, bitmap); } fis.close(); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream( Environment.getExternalStorageDirectory() + "/test.jpg"); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream); Log.v("图片宽度3+图片高度3", bitmap.getWidth() + "+" + bitmap.getHeight()); fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } private Bitmap small(float scale, int w, int l,int degrees, Bitmap bmp) { int bmpWidth = w; int bmpHeight = l; Bitmap tempBmp = null; Matrix matrix = new Matrix(); matrix.postScale(scale, scale); matrix.setRotate(degrees); tempBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, true); return tempBmp; }
/** * 读取照片exif信息中的旋转角度 * * @param path * 照片路径 * @return角度 */ public 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(); } Log.d("翻转角度", degree + ""); return degree; }