Android image compression solution to avoid memory overflow

Many applications in android need to take pictures and upload pictures. As the pixels of mobile phones are getting higher and higher, the pictures taken are also getting bigger and bigger. When displaying after shooting, use universalimageloader. This open source project can avoid memory overflow. However, when uploading, it generally needs to be compressed, but it is easy to cause memory overflow when compressing. The solution is to store the compressed binary stream directly as a local file without exporting Bitmap, and upload it directly through the local file when uploading. code show as below:

1. Image compression to obtain input stream

/**
	 * Compress image to get input stream
	 * @param image
	 * @return
	 */
	public static InputStream compressImage3(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// Quality compression method, where 100 means no compression, store the compressed data in baos
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // Loop to determine if the compressed image is larger than 100kb, and continue to compress
			baos.reset();// Reset baos to clear baos
			options -= 10; // decrease by 10 each time
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// compress options% here, and store the compressed data in baos

		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// Store the compressed data baos in ByteArrayInputStream
		//Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// Generate pictures from ByteArrayInputStream data
		//return bitmap;
		return isBm;
	}
	

 2. Write the input stream to the file, the code is as follows:

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

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326572990&siteId=291194637