现在的位置: 首页 > 综合 > 正文

Android:指定分辨率和清晰度的图片压缩方法源码

2014年10月12日 ⁄ 综合 ⁄ 共 893字 ⁄ 字号 评论关闭

http://www.wizzer.cn/?p=1792

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();
		}
	}

抱歉!评论已关闭.