How Can i set image from imageview in binary body in API endpoint?
I need to get image from an ImageView and put it into a request body that expects a binary value (jpg image) How can I do the bellow API calling in kotlin?
CodePudding user response:
You can convert the Bitmap representation of the image to a ByteArray, and then use it in the request body. Here's an example in Kotlin:
val imageView: ImageView = findViewById(R.id.imageView)
val bitmap = (imageView.drawable as BitmapDrawable).bitmap
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
val imageBytes = byteArrayOutputStream.toByteArray()
CodePudding user response:
There isn't enough context in your question, eg example code. But try the below:
//get drawable from your imageview
Drawabel drawable = imageVIew.getDrawable();
BitmapDrawable bitmapDrawable = ((BitmapDrawable) drawable);
//convert image to binary
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
byte[] imageInByte
is what you asked for, but I have also added conversion to stream in case you end up needing that.