以 base64 格式上传图像和压缩图像,然后再通过改造发送到服务器?

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

我根据互联网教程制作了带有改装的上传图片。 这是我的代码:

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) {

            }
        });

retrofit中如何将图片转成base64压缩后发送到服务器?

试试下面的代码:

首先定义ByteArrayOutputStreambyte[]对象:

bytearrayoutputstream = new ByteArrayOutputStream();
byte[] BYTE;

第二个定义未压缩的 Bitmap (bitmap1) 如下:

 bitmap1.compress(Bitmap.CompressFormat.JPEG,40,bytearrayoutputstream);

 BYTE = bytearrayoutputstream.toByteArray();

第三次将byte[]转换为Base64

 String base64 = Base64.encodeToString(BYTE, Base64.DEFAULT);
 Bitmap compressedBitmap = BitmapFactory.decodeByteArray(BYTE,0,BYTE.length);

四、最后得到CompressedBase64转换后的图片:

现在您可以直接发送 Base64 图片而无需使用 MultiPart