java.lang.OutOfMemoryError:未能分配341424000字节的分配,其中25165824个可用字



每次我想用Base64将视频的字节编码成字符串时,我都会遇到这个错误,我认为视频大小太大,无法编码,因为当我尝试对较小的视频进行编码时,效果很好。

java.lang.OutOfMemoryError: Failed to allocate a 341424000 byte allocation with 25165824 free bytes and 78MB until OOM, target footprint 479725424, growth limit 536870912

这是我的代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 200) {
Uri selectedMediaUri = data.getData();
String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media.MIME_TYPE };
Cursor cursor = getContext().getContentResolver().query(selectedMediaUri, columns, null, null, null);
cursor.moveToFirst();
int pathColumnIndex = cursor.getColumnIndex( columns[0] );
String contentPath = cursor.getString(pathColumnIndex);
cursor.close();
FileInputStream inputStream;
try {
inputStream = new FileInputStream(contentPath);
} catch (Exception e) {
Toast.makeText(getContext(), "Fail to retrieve video data.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
return;
}
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
Client.videoData = Base64.encodeToString(bytes, Base64.DEFAULT);
}
}
}

我试图读取一个以字节为单位的视频文件,然后用Base64将其转换为字符串。但它一直给我这个错误

(注意:我将把它解码回字节,稍后在视频视图中设置它(

那么我该如何解决这个问题呢?请帮忙!

它完全可以通过在命令行上启动程序二进制文件来修复,该二进制文件带有将内存分配给-Xss-Xmx-Xms的JVM的标志,还可以分配一个G1垃圾收集器。在X32中,RAM的数量是有限的,但在X64中,可分配的RAM要大得多。

在Android中对base64进行编码的方法是每次使用少量内存,每次处理3个字节进行编码,4个字节进行方法的例行调用进行未编码。安卓有GC,但我不是安卓开发人员,但这是这个安卓开发页面的推荐。例如,为了避免内存流失,循环中的每个方法调用都会因文件大小计算除法而在缺少任何.3或.6尾部时停止300字节。请参阅链接后的内容。https://developer.android.com/topic/performance/memoryjava.util.Base64编码器具有withoutPadding((方法。正如我所说,你以3的倍数循环文件字节进行编码,只需用双类型数学将文件大小除以3,然后将答案转换为string((和string.indexof";。3〃;一个剩余的或";。6〃;两个剩余字节,并使用通常在这些剩余字节上填充的方法进行调用编码。它没有一个尾垫的确切倍数3与编码。

相关内容

最新更新