[英]Image uploading from android to PHP server using retrofit
我正在使用改造將圖像上傳到服務器。 我將圖像編碼為位圖,然后將位圖轉換為字符串並將字符串傳遞給 PHP。 在 PHP 端,我再次解碼圖像,然后保存到服務器文件夾。 如果我將圖像質量壓縮到 30,它可以完美運行,但如果我將圖像質量設置為 100,應用程序會崩潰並顯示空指針。
這是我的代碼:
結果活動:
if (requestCode == 1 && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
// photo = BitmapFactory.decodeFile(picturePath);
profile_photo =
ImageUtils.getInstant().getCompressedBitmap(picturePath);
Uri tempUri = getImageUri(this, profile_photo);
cursor.close();
profile_image.setImageResource(android.R.color.transparent);
Picasso.get()
.load(tempUri)
.resize(150, 150)
.into(profile_image);
profile_image.setScaleType(ImageView.ScaleType.FIT_XY);
profile_image.setPadding(5, 5, 5, 5);
//Bitmap profile_photo = ((BitmapDrawable)
profile_image.getDrawable()).getBitmap();
upload_profileimage();
b.dismiss();
}
位圖到字符串:
public String BitmapTOString(Bitmap bitmap) {
Bitmap bm = bitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteFormat = stream.toByteArray();
String imgString = Base64.encodeToString(byteFormat, Base64.DEFAULT);
return imgString;
}
改造 API 調用:
call = user_profileimge_interface.profileImage_uplaod(BitmapTOString(profile_photo), user_id);
PHP代碼:
$data = $baseurl.'user_profile_pictures/'.$user_id.".JPEG";
file_put_contents($data, base64_decode($profile_picture));
echo json_encode(Array('message' => "image inserted"));
API接口:
@POST("update_profilepic.php")
Call<Profile_Image_updateJson> profileImage_uplaod(@Query("profile_picture") String profileImage,
@Query("user_id") String user_id);
我建議將位圖作為二進制數據發送,而不是轉換為/從字符串。 例如:
@POST
Call<Profile_Image_updateJson> profileImage_uplaod(@Query("user_id") String user_id, @Body RequestBody body);
然后是這樣的:
requestBody = RequestBody.create(MediaType.parse("image/jpeg"), imageBytes)
call = user_profileimge_interface.profileImage_uplaod(user_id, requestBody);
嘗試在單獨的線程中執行BitmaptoString()
操作,遠離主 UI 線程。
如果在主 UI 線程中執行位圖處理成本太高,則應用程序可能會崩潰。 此外,您可以使用Asynctask
或 Any Background Process 來執行代價高昂的功能並避免在主線程中進行任何代價高昂的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.