【发布时间】:2017-03-08 16:47:27
【问题描述】:
每个人。我被困在我正在从事的这个项目上。我希望能够从 android 库上传图像,将该图像编码为 base64 字符串并作为 get 变量发送到 PHP Web 服务,然后从另一端解码图像并按照我的意愿进行处理。
到目前为止,我能够从图库中选择图像,甚至可以编码为 base64 字符串并存储在 android 首选项中。
问题是,我认为并非所有字符串都被发送到 PHP 服务(有些被截断)。
我为什么这么认为?我的 Log.d 在转储到不同位置时向我显示了不同的字符串。
获取图像并编码的代码是:-
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Please select a file"),1);
}
private String onSelectFromGalleryResult (Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver() , data.getData()) ;
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;
byte[] imageBytes = byteArrayOutputStream.toByteArray() ;
Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ;
return Base64.encodeToString (imageBytes, Base64.DEFAULT) ;
} else {
return null ;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit() ;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
/*Here we handle the image gotten from the gallery*/
String encodedGalleryImage = onSelectFromGalleryResult(data);
editor.putString("userEncodedGalleryImage" , encodedGalleryImage);
} else if (requestCode == 0) {
/*Here we handle the image that was take using the camera*/
}
editor.apply();
}
}
这里我们称之为 asynctask 类
private void callAsynctask () {
SharedPreferences sp = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
String userQuestionAttachement = sp.getString("userEncodedGalleryImage" , "") ;
Log.d("callingEncodedImage" , userQuestionAttachement) ;
}
我遇到的问题是来自 Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) 的日志;与 Log.d("callingEncodedImage" , userQuestionAttachement) 不同;
两者的开头相同,但结尾不同。我希望看到相同的字符。
有人可以帮我解决吗?
【问题讨论】:
-
base64 字符串有时可能太大而无法一次性发送。更好的选择是使用多部分上传图像文件。
-
你好@VivekMishra 你会怎么做?我想这就是我需要的!...
标签: php android image android-asynctask