问题
I've make upload image with retrofit that i follow from tutorial in internet. here are my code:
AcademicClient.class
@Multipart
@POST("/")
Call<ResponseBody> postImage(@Part MultipartBody.Part image, @Part("name")RequestBody name);
MainFeed.class
File file = new File(filePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload",file.getName(),reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"),"upload_test");
Log.d("xxxxxxx",body + " ---- "+ name);
AcademicClient client = ServiceGenerator.createService(AcademicClient.class);
Call<ResponseBody> call = client.postImage(body,name);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
How to convert it Base64 and compress the image first before it sending to server in retrofit?
回答1:
Try below code:
First define ByteArrayOutputStream
and byte[]
object:
bytearrayoutputstream = new ByteArrayOutputStream();
byte[] BYTE;
Second define uncompressed Bitmap
(bitmap1) like below:
bitmap1.compress(Bitmap.CompressFormat.JPEG,40,bytearrayoutputstream);
BYTE = bytearrayoutputstream.toByteArray();
Third convert byte[]
to Base64
String base64 = Base64.encodeToString(BYTE, Base64.DEFAULT);
Bitmap compressedBitmap = BitmapFactory.decodeByteArray(BYTE,0,BYTE.length);
Fourth, finally you get Compressed
and Base64
converted image:
Now you can send Base64
image directly without using MultiPart
.
来源:https://stackoverflow.com/questions/46360249/upload-image-in-base64-format-and-compressed-image-before-sending-to-server-with