开发的过程中,经常会选择上传图片,有时图片过大,需要裁剪。
以下是图片裁剪的方法。
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回的bitmap为null,此句代码不可删除,切记 int outHeight = options.outHeight; int outWidth = options.outWidth; int heightRatio = Math.round((float) outHeight / (float) 800); int widthRatio = Math.round((float) outWidth / (float) 480); int SampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; int upwidth = Math.round((float) outWidth / (float) SampleSize); int upheight = Math.round((float) outHeight / (float) SampleSize);//参数说明,要压缩的图片路径,压缩后的图片路径,宽,高,图片质量 transImage(path, GlobalFilePath.CACHE_IMAGE + uuid + ".jpg", upwidth, upheight, 90);
//压缩图片大小 public void transImage(String fromFile, String toFile, int width, int height, int quality) { try { Bitmap bitmap = BitmapFactory.decodeFile(fromFile); int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); // 缩放图片的尺寸 float scaleWidth = (float) width / bitmapWidth; float scaleHeight = (float) height / bitmapHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 产生缩放后的Bitmap对象 Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false); // save file File myCaptureFile = new File(toFile); FileOutputStream out = new FileOutputStream(myCaptureFile); if (resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) { out.flush(); out.close(); } if (!bitmap.isRecycled()) { bitmap.recycle();//记得释放资源,否则会内存溢出 } if (!resizeBitmap.isRecycled()) { resizeBitmap.recycle(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
以上方法就是压缩图片大小的方法。