【问题标题】:upload image in base64 format and compressed image before sending to server with retrofit?在通过改造发送到服务器之前上传base64格式的图像和压缩图像?
【发布时间】:2019-01-11 16:48:17
【问题描述】:

我已经根据互联网上的教程进行了改进并上传了图片。 这是我的代码:

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

            }
        });

如何将其转换为Base64并先压缩图像,然后再将其发送到改造中的服务器?

【问题讨论】:

    标签: java android retrofit image-compression


    【解决方案1】:

    试试下面的代码:

    首先定义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

    【讨论】:

    • 我有点困惑,我还是安卓开发的新手。我的 AcademicClient 课程和 maindfeed 课程有什么变化吗?因为你说我可以不使用 Multipart 发送?
    • 感谢您的回答:)
    • @niveshshastri 如何在没有 MultiPart 的情况下将 Bae64 字符串发送到服务器?
    • @PradeepSodhi 这里不需要使用 multipart,只需在 POST API 中使用键值格式
    猜你喜欢
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 2017-05-17
    • 2017-05-21
    • 2017-09-10
    相关资源
    最近更新 更多