2016-10-17 74 views
-4

我已經嘗試了互聯網上的多種解決方案,但沒有運氣,如何在上載應用程序時更改圖像大小? 我希望它能夠以上傳2MB文件的方式發送到大小爲50kb的服務器。 請幫我在發送到服務器之前,android會將圖像大小壓縮

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    //get image thumbnail 
    if (requestCode == REQUEST_CODE_PICKER && resultCode == RESULT_OK && data != null) { 

     ArrayList<Image> images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES); 

     absolutePath = null; 
     // do your logic .... 
     for (Image img : images) { 
      Log.v(LOG_TAG, img.getName() + " " + img.getPath()); 
      absolutePath = img.getPath(); 
      absolutePath = String.valueOf(Compressor.getDefault(getContext()).compressToFile(imageFile)); 
      Bundle bundleExtras = data.getExtras(); 
      image = (Bitmap) bundleExtras.get("data"); 
     } 
     consultantProfileImageView.setImageBitmap(getBitmapFromPath(absolutePath)); 
     new UploadConsultantProfileImageTask(getContext(), absolutePath).execute(); 
     postConsultant(); 
    } 

} 

public File getBitmapFromPath(String filePath) { 
    File imageFile = new File(filePath); 
    Bitmap imageBitmap = null; 
    imageBitmap = BitmapFactory.decodeFile(filePath); 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    InputStream in = new ByteArrayInputStream(bos.toByteArray()); 
    File compressedImageFile = Compressor.getDefault(getContext()).compressToFile(imageFile); 
    if (compressedImageFile.exists()) { 
     imageBitmap = BitmapFactory.decodeFile(compressedImageFile.getAbsolutePath()); 
    } 

    return compressedImageFile; 
} 
+2

「我試圖從沒有運氣互聯網多種解決方案」 - 請解釋一下你試了一下(通過[MCVE]),並具體是什麼「沒有運氣」是指相對於你嘗試過什麼。 「當我上傳2MB文件時」 - 請詳細解釋**這是什麼類型的文件(PNG,JPEG,RAW,GIF,WEBP等)以及您存儲的文件的位置。 – CommonsWare

+0

你想讓你的應用程序壓縮圖像,或者你打算手動完成嗎?請更好地解釋你的問題.. – Rippr

+0

我的應用程序應該允許用戶添加個人資料圖片然後裁剪/壓縮到50kb,然後將其保存到服務器 – Fuluza

回答

0

嘗試使用下面將圖像壓縮到80%。您可以根據您的要求更改壓縮比例。

public File getBitmapFromPath(String filePath) { 
     File imageFile = new File(filePath); 
     OutputStream fout = new FileOutputStream(file); 
     Bitmap bitmap= BitmapFactory.decodeFile(filePath); 
     bitmap.compress(CompressFormat.JPEG, 80, fout); 
     fout.flush(); 
     fout.close(); 

     return imageFile; 
} 
+0

我試過它沒有工作。對於那些可能面臨同樣問題的人,我使用https://android-arsenal.com/details/1/3758上的這個庫,它的功能就像一個魅力! – Fuluza

相關問題