我正在编写代码以允许用户从图库中选择图像并使用 Base64 将其上传到服务器。一切正常,直到我在 API > 19 上测试代码并收到错误。
这是我的代码:
// Upload Image :)
camera.setOnClickListener(new OnClickListener () {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}});
} // End Of On Create
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap image =BitmapFactory.decodeFile(imagepath);
imageView_pic.setImageBitmap(image);
imageData = encodeTobase64(image);
Toast.makeText(Share_event_experience.this, imagepath, Toast.LENGTH_LONG).show();
}
}
public static String encodeTobase64(Bitmap image) {
System.gc();
if (image == null) return null;
Bitmap immagex = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); // min minSdkVersion 8
return imageEncoded;
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
然后我使用 ASyncTask 将值“imageData”发送到 php 文件。
当我尝试使用 API > 19 时出现的错误:
04-15 10:16:07.497: E/BitmapFactory(1357): Unable to decode stream: java.lang.NullPointerException