【发布时间】:2014-01-30 17:17:49
【问题描述】:
我正在尝试将图像编码为 64 base ,
从图库中选择图片并尝试保存后,我收到此错误:
内存不足异常
任何人都可以建议如何将此图像设置为 base 64 而不会出现内存错误?
MotorImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
@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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
//
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
String imageString = null;
try {
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
bm.recycle();
byte[] b = baos.toByteArray();
imageString = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), imageString, Toast.LENGTH_SHORT).show();
【问题讨论】:
-
不要写入
ByteArrayOutputStream,不要写入文件、网络套接字……你不能将任意大的数据写入内存。也不要编码为String,因为那也会写入内存。也有输出流。 -
我想将它保存为字符串因为我将它存储在 sql server 数据库中,我应该使用什么?
-
您不需要
String,您也可以将其流式传输到您的服务器。如何取决于您的服务器和许多其他因素。 -
base64-ing 图像真的不是一个好主意,应该避免。
-
对文件使用 Base64OutputStream。
标签: java android filestream