在Android中使用Base64上傳圖片
阿新 • • 發佈:2019-02-19
1.伺服器介面引數
後臺已經給出了具體的引數,所以使用base64上傳圖片也是分分鐘的事情了。
步驟1
獲取需要上傳圖片的路徑:(這裡直接給出專案的部分程式碼)
//把bitmap轉換成String public String bitmapToString(String filePath) { Bitmap bm = getSmallBitmap(filePath); ByteArrayOutputStream baos = new ByteArrayOutputStream(); //1.5M的壓縮後在100Kb以內,測試得值,壓縮後的大小=94486位元組,壓縮後的大小=74473位元組//這裡的JPEG 如果換成PNG,那麼壓縮的就有600kB這樣 bm.compress(Bitmap.CompressFormat.JPEG, 40, baos); byte[] b = baos.toByteArray(); Log.d("d", "壓縮後的大小=" + b.length); return Base64.encodeToString(b, Base64.DEFAULT); } // 根據路徑獲得圖片並壓縮,返回bitmap用於顯示 public Bitmap getSmallBitmap(String filePath) { final BitmapFactory.Optionsoptions = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, 480, 800); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); }
ok ! 搞定0.0~