我正在尝试将图像编码为64碱基,
从图库中选择图片并尝试保存后,我收到此错误:
outOfMemory Exception
任何人都可以建议如何在没有内存错误的情况下将此映像设置为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();
答案 0 :(得分:2)
我怀疑你需要缩放和重新采样你的图像以适应设备的限制,试试这样的事情
// 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;
}
答案 1 :(得分:0)
尝试在AndroidManifest上的应用程序代码中使用android:largeHeap="true"
,然后您的应用程序将拥有更多内存,并且不会引发异常。
答案 2 :(得分:0)
如果您阅读了android的官方文档,您将会发现这是android的常见问题,建议的解决方案是根据您的需要调整图像大小。您也可以参考developer.android