在通过改造发送到服务器之前上传 base64 格式的图像和压缩图像? [英] upload image in base64 format and compressed image before sending to server with retrofit?

查看:43
本文介绍了在通过改造发送到服务器之前上传 base64 格式的图像和压缩图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过改造上传图片,我从互联网上的教程中遵循.这是我的代码:

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

            }
        });

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

How to convert it Base64 and compress the image first before it sending to server in retrofit?

推荐答案

试试下面的代码:

首先定义ByteArrayOutputStreambyte[]对象:

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

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

Second define uncompressed Bitmap (bitmap1) like below:

 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转换后的图片:

Fourth, finally you get Compressed and Base64 converted image:

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

Now you can send Base64 image directly without using MultiPart.

这篇关于在通过改造发送到服务器之前上传 base64 格式的图像和压缩图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆