Android/Kotlin

그래픽 라이브러리 없이 Retrofit만 사용하여 이미지 출력

lipnus 2018. 11. 28. 13:10
반응형


1. Gradle

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'


2. Permission

<uses-permission android:name="android.permission.INTERNET" />


3. Interface(Retrofit)
interface RetrofitImageAPI {

@GET("api/RetrofitAndroidImageResponse")
fun getImageDetails(): Call<ResponseBody>

}



4. MainActivity.kt

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

btnEvent()
}


//버튼클릭
fun btnEvent(){

btn_showimg.setOnClickListener {
getRetrofitImage()
}
}


internal fun getRetrofitImage() {

val url = "http://www.androidtutorialpoint.com/"

val retrofit = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()

val service = retrofit.create(RetrofitImageAPI::class.java)

val call = service.getImageDetails()

call.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
try {

Log.d("onResponse", "Response came from server")

val FileDownloaded = DownloadImage(response.body()!!)

Log.d("onResponse", "Image is downloaded and saved ? $FileDownloaded")

} catch (e: Exception) {
Log.d("onResponse", "There is an error")
e.printStackTrace()
}

}


override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
Log.d("onFailure", t.toString())
}

})
}


private fun DownloadImage(body: ResponseBody): Boolean {

try {
Log.d("DownloadImage", "Reading and writing file")
var inputStream: InputStream? = null
var outputStream: FileOutputStream? = null

try {
inputStream = body.byteStream()
outputStream = FileOutputStream(getExternalFilesDir(null).toString() + File.separator + "AndroidTutorialPoint.jpg")
var c: Int

do{
c = inputStream.read()
outputStream.write(c)
} while(c != -1)

} catch (e: IOException) {
Log.d("DownloadImage", e.toString())
return false
} finally {
inputStream?.close()
outputStream?.close()
}

val width: Int
val height: Int
val bMap = BitmapFactory.decodeFile(getExternalFilesDir(null).toString() + File.separator + "AndroidTutorialPoint.jpg")
width = 2 * bMap.width
height = 6 * bMap.height
val bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false)
iv_test.setImageBitmap(bMap2)

return true

} catch (e: IOException) {
Log.d("DownloadImage", e.toString())
return false
}

}
}



반응형

'Android > Kotlin' 카테고리의 다른 글

Intent  (0) 2018.11.28
JSON형식을 Kotlin 데이터클래스로 만들기  (0) 2018.11.28
WebView  (0) 2018.11.27
Jsoup  (0) 2018.11.26
[문법] While문에서 assignment 불가능  (0) 2018.11.25