我正在尝试将图像编码为 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();
最佳答案
我怀疑您需要对图像进行缩放和重新采样以适应设备的限制,尝试这样的操作
// decodes image and scales it to reduce memory consumption
private Bitmap decodeImage(String picturePath) {
try {
File file = new File(picturePath);
// Get image size
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file), null, opts);
// The new size we want to scale to
final int MIN_SIZE = 70;
// Find the correct scale value.
int scale = 1;
while (((opts.outWidth / scale) >> 1) >= MIN_SIZE
&& ((opts.outHeight / scale) >> 1) >= MIN_SIZE) {
scale <<= 1;
}
BitmapFactory.Options opts2 = new BitmapFactory.Options();
opts2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(file), null, opts2);
} catch (FileNotFoundException e) {
}
return null;
}
关于java - 重新编码图像时出现内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21463135/