工作筆記之圖片壓縮上傳

  今天遇到一個問題:android端imageview加載一個幾M的圖片,顯示特別慢,會讓人產生沒有顯示的錯覺。

然後我是這樣解決的:新建一個bitmap,調方法壓縮文件,返回bitmap

/**
 *通過獲取地址後,壓縮圖片,爲100KB以下,然後上傳
 * @param path
 * @return
 * @throws IOException
 */
public static Bitmap revitionImageSize(String path) throws IOException {
   BufferedInputStream in = new BufferedInputStream(new FileInputStream(
         new File(path)));
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeStream(in, null, options);
   in.close();
   int i = 0;
   Bitmap bitmap = null;
   while (true) {
      if ((options.outWidth >> i <= 1000)
            && (options.outHeight >> i <= 1000)) {
         in = new BufferedInputStream(
               new FileInputStream(new File(path)));
         options.inSampleSize = (int) Math.pow(2.0D, i);
         options.inJustDecodeBounds = false;
         bitmap = BitmapFactory.decodeStream(in, null, options);
         break;
      }
      i += 1;
   }
   return bitmap;
}

然後設置ImageView的src爲Bitmap就可以了。

接着是上傳,我查了很多資料,大多數是這樣:新建一個文件,再把bitmap寫進去文件流裏面。然後再拿這個新的文件上傳服務器。

File file = new File(filepath);
String pathhead = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());
//getCacheDir這個方法是拿到當前app的緩存路徑
File file1 = new File(ApplicationXPMedical.getInstance().getCacheDir(), pathhead);
try {
FileOutputStream fos = new FileOutputStream(file1);
fos.write(Bitmap2Bytes(bit));
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}

	/**
	 *bitmap轉換爲字節
	 * @param bm
	 * @return
	 */
	public static byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}


 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章