我已经编写了使用okhttp和kotlin将图像上传到服务器的代码,即用户通过相机拍摄图片,然后在用户单击发送按钮时在imageView中显示图像,我希望从ImageView中获取图像发送到服务器,但是我不知道如何将ImageView中的图像更改为可以发送到服务器的文件,请查看我的代码以获取更多详细信息
这是我的kotlin代码
fun uploadImage(url:String, image:File, imageName:String){
val MEDIA_TYPE_PNG = MediaType.parse("image/png")
val client = OkHttpClient()
val requestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", imageName, RequestBody.create(MEDIA_TYPE_PNG, image))
.build()
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
client.newCall(request).enqueue(object:Callback{
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
Log.i(TAG,"response ${response.body?.string()}")
}
})
}
问题是,如何将图像从imageView转换为“ image:File”以进行uploadImage功能?
答案 0 :(得分:0)
希望获得帮助
val url = getString(R.string.urlUpload)
val MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg")
val bitmap = (img_register.drawable as BitmapDrawable).bitmap
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val bitmapByteArray = baos.toByteArray()
val file = Base64.encodeToString(bitmapByteArray,Base64.DEFAULT)