簡體   English   中英

在使用 Retrofit2 上傳到服務器之前調整圖像文件的大小

[英]Resize image file before uploading to server using Retrofit2

我正在嘗試使用 Retrofit 將圖像上傳到服務器,但現在我面臨圖像尺寸太大的問題。 這是我的代碼:

private fun uploadImageFileToApiServer(){
    Log.e("api", "start")
    var file: File?= null
    try{

        file = File(Common.getFilePath(this, selectedUri!!))
        Log.e("FilePath", file.toString())

    }catch(e: URISyntaxException) {e.printStackTrace()}


    if(file != null)
    {
        val requestBody = ProgressRequestBody(file, this)

        //how can i resize the image here before uploading it to server???


        val body = MultipartBody.Part.createFormData("image", file.name, requestBody)
        Thread(Runnable {
            mService.uploadFile(body) 
                .enqueue(object: Callback<String> {
                    override fun onFailure(call: Call<String>, t: Throwable) {
                        Toast.makeText(this@ApiProcessing, t.message, Toast.LENGTH_LONG).show()
                        Log.e("api", t.message!!)
                    }

                    override fun onResponse(call: Call<String>, response: Response<String>) {
                        val stringResponse = response.body()?.toString()

                        try {
                            val jsonObject = JSONObject(stringResponse)
                            val label = jsonObject.getString("label")
                            val width = jsonObject.getString("width")
                            val height = jsonObject.getString("height")
                            HaveFruitResult.label = label
                            HaveFruitResult.width = width
                            HaveFruitResult.height = height
                 
                        }
                        catch (e: NullPointerException){
                            Toast.makeText(this@ApiProcessing, e.message, Toast.LENGTH_LONG).show()
                            //moveToMainActivity()
                            val handler = Handler()
                            handler.postDelayed({
                                moveToMainActivity()
                            }, 4000)
                        }
                    }
                })

        }).start()
    }
    else
    {
        Toast.makeText(this@ApiProcessing, "Fail!!", Toast.LENGTH_LONG).show()
    }
    Log.e("api", "end")
}

因為圖片太大,上傳需要很長時間,所以有時我無法從 API 服務器獲取響應。 這是我的 IUploadAPI

interface IUploadAPI {
@Multipart
@POST("/fruit_vision_api")
fun uploadFile(@Part file: MultipartBody.Part) : Call<String>
}

我怎么解決這個問題? 非常感謝您的幫助!!!!!!!!!

我正在使用此對象將圖像壓縮到最大 1Mo。 您可以使用它或根據您的需要進行調整

/**
 * Definition of the BitmapUtils object.
 */
object BitmapUtils {
    const val ONE_KO = 1024
    const val ONE_MO = ONE_KO * ONE_KO

    /**
     * Compress, if needed, an image file to be lower than or equal to 1 Mo
     *
     * @param filePath Image file path
     *
     * @return Stream containing data of the compressed image. Can be null
     */
    fun compressedImageFile(filePath: String): InputStream? {
        var quality = 100
        var inputStream: InputStream? = null
        if (filePath.isNotEmpty()) {
            var bufferSize = Integer.MAX_VALUE
            val byteArrayOutputStream = ByteArrayOutputStream()
            try {
                val bitmap = BitmapFactory.decodeFile(filePath)
                do {
                    if (bitmap != null) {
                        byteArrayOutputStream.reset()
                        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream)
                        bufferSize = byteArrayOutputStream.size()
                        logD { "quality: $quality -> length: $bufferSize" }
                        quality -= 10
                    }
                } while (bufferSize > ONE_MO)
                inputStream = ByteArrayInputStream(byteArrayOutputStream.toByteArray())
                byteArrayOutputStream.close()
            } catch (e: Exception) {
                logE { "Exception when compressing file image: ${e.message}" }
            }
        }
        return inputStream
    }
}

要從 InputStream 創建文件,您可以使用此擴展名:

fun File.copyInputStreamToFile(inputStream: InputStream) {
    this.outputStream().use { fileOut ->
        inputStream.copyTo(fileOut)
    }
}

並使用它:

var file = File(YOUR_PATH)
file.copyInputStreamToFile(BitmapUtil.compressedImageFile(filePath))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM