我正在使用改型将图像上传到服务器。我将图像编码为位图,然后将位图转换为字符串并将字符串传递给PHP。在PHP方面,我再次解码图像,然后将其保存到服务器文件夹。 如果我将图像质量压缩到30,但是将应用设置为100时,应用崩溃并显示空指针,则效果很好。
这是我的代码:
ResultActivity:
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;
}
Retrofit 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);
答案 0 :(得分:2)
我建议将位图作为二进制数据发送,而不是转换为字符串或从字符串转换为位图。例如:
@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);
答案 1 :(得分:1)
尝试在独立于主UI线程的单独线程中执行BitmaptoString()
操作。
如果在主UI线程中执行位图处理成本太高,则该应用程序可能会崩溃。另外,您可以使用Asynctask
或任何后台进程来执行昂贵的功能,并避免在主线程中进行任何昂贵的操作。