gpt4 book ai didi

java - Android 将图库中的图像转换为 base64 导致 OutOfMemory 异常

转载 作者:太空狗 更新时间:2023-10-29 15:54:09 25 4
gpt4 key购买 nike

我想从图库中加载图像,然后将其转换为 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();


}


}

最后,我想解码位于 picutrePathimage

                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)

谁能指出我哪里做错了?

最佳答案

我建议改变

Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//added lines
bm.recycle();
bm = null;
//added lines
byte[] b = baos.toByteArray();
b64=Base64.encodeToString(b, Base64.DEFAULT);

这样,您就不会将位图加载到应用内存中两次。

关于java - Android 将图库中的图像转换为 base64 导致 OutOfMemory 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17278314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com