android 图片压缩避免内存溢出的解决办法

在android中的很多应用中都需要拍照上传图片,随着手机的像素越来越高,拍摄的图片也越来越大。在拍摄后显示的时候,使用universalimageloader.这个开源项目可以避免内存溢出。但是在上传的时候,一般需要压缩,但是压缩的时候很容易导致内存溢出。解决的办法就是,压缩后的二进制流,不用导出Bitmap,而是直接存储为本地文件,上传的时候直接通过本地文件上传。代码如下:

1.图片压缩获取输入流

/**
	 * 压缩图片获取输入流
	 * @param image
	 * @return
	 */
	public static InputStream compressImage3(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			options -= 10;// 每次都减少10
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中

		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		//Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		//return bitmap;
		return isBm;
	}
	

 2.将输入流写入文件,代码如下:

InputStream in=ImageLoadUtil.compressImage3(bitmap);
		
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			FileOutputStream out = new FileOutputStream(file);
			byte[] buf=new byte[64];
			int len;
			while((len=in.read(buf))>-1){
				out.write(buf, 0, len);
			}
			//bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

猜你喜欢

转载自alex-yang-xiansoftware-com.iteye.com/blog/2319246