upload image in base64 format and compressed image before sending to server with retrofit?

青春壹個敷衍的年華 提交于 2019-12-23 05:05:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!