我想从图库中加载图像,然后将其转换为 base64。
这听起来并不难。所以我这样做了:
首先打开画廊并选择图片:
picteureBtn.setOnClickListener(new View.OnClickListener() {
private Uri imageUri;
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
第二个onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && 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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
最后我想解码我image
的picutrePath
String b64;
StringEntity se;
String entityContents="";
if (!picturePath.equals("")){
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
b64=Base64.encodeToString(b, Base64.DEFAULT);
}
不幸的是,我得到:
06-24 16:38:14.296: E/AndroidRuntime(3538): FATAL EXCEPTION: main
06-24 16:38:14.296: E/AndroidRuntime(3538): java.lang.OutOfMemoryError
06-24 16:38:14.296: E/AndroidRuntime(3538): at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
谁能指出我在哪里做错了?