我正在使用改造将图像上传到服务器。我将图像编码为位图,然后将位图转换为字符串并将字符串传递给 PHP。在 PHP 端,我再次解码图像,然后保存到服务器文件夹。 如果我将图像质量压缩到 30,它会完美运行,但如果我将图像质量设置为 100,应用程序会崩溃并显示空指针。
这是我的代码:
结果 Activity :
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接口(interface):
@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);
关于java - 使用 Retrofit 将图像从 Android 上传到 PHP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52245168/