在发送到服务器并进行改造之前,以base64格式和压缩图像上传图像?

时间:2017-09-22 08:31:11

标签: java android retrofit image-compression

我使用互联网上的教程进行改造后上传图片。 这是我的代码:

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并在改造之前先将图像压缩到服务器上?

1 个答案:

答案 0 :(得分:2)

尝试以下代码:

首先定义Product name=Misha Black Cropped Leather Jacket With Asymmetrical Front Zipper Retailer=Mackage Size:XXS Size:M ByteArrayOutputStream对象:

byte[]

第二个定义未压缩的bytearrayoutputstream = new ByteArrayOutputStream(); byte[] BYTE; (bitmap1),如下所示:

Bitmap

第三次将 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); Compressed转换后的图片:

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