![](/img/trans.png)
[英]Sending image from android to java Server which is running Restful webservice?
[英]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.