繁体   English   中英

如何使用 Retrofit 将包含图像的类从 Android 发送到 Java Restful Web 服务器

[英]How to send class which contain Image from Android to Java Restful Web server using Retrofit

我使用 Retrofit 将数据(类)从 android 传输到服务器。通常我们在客户端和服务器端创建相同的类,其中包含双方相同的数据类型,如 int、String。现在我需要将类中的图像发送到服务器。另外我只是不想将图像发送到服务器,但我想发送包含 1 个图像作为数据类型的类。那么我该怎么做?或者有什么建议我怎么能用其他工具做到这一点?

假设您已经有一个指向图像的File

final File imageFile = ...;

注意:如何获取此文件取决于您是否只允许文件选择器中的本地文件(或例如实际在 Google Drive 中的图像)以及您使用的 Android 版本等。

要上传您需要使用 Retrofit 的TypedFile的图像 - 这对我TypedFile

@POST("/api/image/upload")
@Multipart
public void submitPictureToVoting(@Part("user_id") Integer userId,
                                  @Part("image_title") String imageTitle,
                                  @Part("file") TypedFile file,
                                  Callback<UploadImageResponse> callback);

进而:

final TypedFile typedImageFile = new TypedFile("application/octet-stream", imageFile);

mApiClient.submitPictureToVoting(
    1234567,
    "This is me!",
    typedImageFile,
    new Callback<UploadImageResponse> {
        // ...
    });

我不认为这是答案,但通过这样做我们可以轻松解决改造问题

嗨,我通过将图像编码为字符串进行了尝试,这样我们就可以像其他字符串一样轻松发送此“字符串”数据类型,并且当我们想要返回图像时,我们可以对其进行解码。

1.编码代码

这里的图像取自 ImageView。

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

2.解码代码

 byte[] decodedByte = Base64.decode(encodedImage, 0);
 Bitmap decodedImg= BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
 imageView.setImageBitmap(decodedImg);
  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM