如何使用Retrofit/Android将位图发布到服务器 [英] How to POST a bitmap to a server using Retrofit/Android

查看:78
本文介绍了如何使用Retrofit/Android将位图发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Android Retrofit 将位图发布到服务器.

I'm trying to post a bitmap to a server using Android and Retrofit.

目前,我知道如何发布文件,但我希望直接发送位图.

Currently I know how to post a file, but I'd prefer to send a bitmap directly.

这是因为用户可以从设备上拾取任何图像.我想调整它的大小以节省带宽,然后再将其发送到服务器,并且最好不必加载,调整大小,将其另存为文件并保存到本地存储中,然后发布该文件.

This is because the user can pick any image off their device. I'd like to resize it to save bandwidth before it gets sent to the server and preferrably not have to load it, resize it, save it as a file to local storage then post the file.

任何人都知道如何从 Retrofit 发布位图吗?

Anyone know how to post a bitmap from Retrofit?

推荐答案

注意:在Main以外的其他线程上进行此转换.RxJava可以帮助实现这一目标,或者协程

首先将位图转换为文件

//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        fos.write(bitmapdata);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

此后,使用 Multipart 创建一个请求以上传文件

After that create a request with Multipart in order to upload your file

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), f);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", f.getName(), reqFile);

您的服务电话应如下所示

Your service call should look like this

interface Service {
    @Multipart
    @POST("/yourEndPoint")
    Call<ResponseBody> postImage(@Part MultipartBody.Part image);
}

然后只需调用您的api

And then just call your api

Service service = new Retrofit.Builder().baseUrl("yourBaseUrl").build().create(Service.class);
Call<okhttp3.ResponseBody> req = service.postImage(body);
req.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
         // Do Something with response
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        //failure message
        t.printStackTrace();
    }
});

这篇关于如何使用Retrofit/Android将位图发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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