2

I am trying to do a get request from a client get call to my server. My server response with a image/png content type. How can I recieve the image from my kotlin code?

3 Answers3

1

You can download not only an image but also any other file.

Create ktor-client as you usually do.

val client = HttpClient(OkHttp) {
    install(ContentNegotiation) {
        json(Json { isLenient = true; ignoreUnknownKeys = true })
    }
}

For downloading a file using this client, read response using bodyAsChannel() which reads the response as ByteReadChannel. Use copyAsChannel() to write the data on the disk, passing destination's ByteWriteChannel.

GlobalScope.launch(Dispatchers.IO) {
    val url = Url("FILE_DOWNLOAD_LINK")
    val file = File(url.pathSegments.last())
    client.get(url).bodyAsChannel().copyAndClose(file.writeChannel())
    println("Finished downloading..")
}
Praveen
  • 3,186
  • 2
  • 8
  • 23
0

If you do not need to save image in storage, you can use byteArray memory source to decode image.

If larger images are expected it would be good to downscale them prior decoding, see here (Android) Android: BitmapFactory.decodeStream() out of memory with a 400KB file with 2MB free heap

Also note that Ktor api often changes from version to version, in this sample the ktor_version = '2.0.0' is used.

val client = HttpClient(Android) { install(Logging) { level = LogLevel.ALL } }

suspend fun getBitmap(uri: Uri): Bitmap? {
    return runCatching {
        val byteArray = withContext(Dispatchers.IO) {
            client.get(Url(uri.toString())).readBytes()
        }

        return withContext(Dispatchers.Default) {
            ByteArrayInputStream(byteArray).use {
                val option = BitmapFactory.Options()
                option.inPreferredConfig = Bitmap.Config.RGB_565 // To save memory, or use RGB_8888 if alpha channel is expected 
                BitmapFactory.decodeStream(it, null, option)
            }
        }
    }.getOrElse {
        Log.e("getBitmap", "Failed to get bitmap ${it.message ?: ""}" )
        null
    }
}
Kurovsky
  • 1,081
  • 10
  • 25
-1

You're going to want to serve static content from your Ktor server: https://ktor.io/docs/serving-static-content.html

You create a static folder, then put your images in there:

static("/") {
    staticRootFolder = File("files")
}

After that's set up, you can reference files in that folder. If you want files in subfolders as well, you can add an extra files(".") line:

static("/") {
    staticRootFolder = File("files")
    files(".")
}
MFazio23
  • 1,261
  • 12
  • 21