Retrofit API to retrieve a png image

后端 未结 8 1295
我在风中等你
我在风中等你 2020-12-02 20:32

Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don\'t know how to download a png using retrofit. I am trying to

8条回答
  •  星月不相逢
    2020-12-02 20:55

    Details

    • Android studio 3.1.4
    • Kotlin 1.2.60
    • Retrofit 2.4.0
    • checked in minSdkVersion 19

    Solution

    object RetrofitImage

    object RetrofitImage {
    
        private fun provideRetrofit(): Retrofit {
            return Retrofit.Builder().baseUrl("https://google.com").build()
        }
    
        private interface API {
            @GET
            fun getImageData(@Url url: String): Call
        }
    
        private val api : API by lazy  { provideRetrofit().create(API::class.java) }
    
        fun getBitmapFrom(url: String, onComplete: (Bitmap?) -> Unit) {
    
            api.getImageData(url).enqueue(object : retrofit2.Callback {
    
                override fun onFailure(call: Call?, t: Throwable?) {
                    onComplete(null)
                }
    
                override fun onResponse(call: Call?, response: Response?) {
                    if (response == null || !response.isSuccessful || response.body() == null || response.errorBody() != null) {
                        onComplete(null)
                        return
                    }
                    val bytes = response.body()!!.bytes()
                    onComplete(BitmapFactory.decodeByteArray(bytes, 0, bytes.size))
                }
            })
        }
    }
    

    Usage 1

    RetrofitImage.getBitmapFrom(ANY_URL_STRING) {
       // "it" - your bitmap
       print("$it")
    }
    

    Usage 2

    Extension for ImageView

    fun ImageView.setBitmapFrom(url: String) {
        val imageView = this
        RetrofitImage.getBitmapFrom(url) {
            val bitmap: Bitmap?
            bitmap = if (it != null) it else {
                // create empty bitmap
                val w = 1
                val h = 1
                val conf = Bitmap.Config.ARGB_8888
                Bitmap.createBitmap(w, h, conf)
            }
    
            Looper.getMainLooper().run {
                imageView.setImageBitmap(bitmap!!)
            }
        }
    }
    

    Usage of the extension

    imageView?.setBitmapFrom(ANY_URL_STRING)
    

提交回复
热议问题