gpt4 book ai didi

Android:上传图像数量导致堆大小变大 - 如何解决?

转载 作者:搜寻专家 更新时间:2023-11-01 09:13:18 31 4
gpt4 key购买 nike

我正在编写应用程序,用户可以在其中拍摄大量照片(最多 20 张)并上传到服务器。图片需要一起上传。

这是我的逻辑:

  1. 拍摄每张照片,在屏幕上显示缩略图并将 SD 上的照片调整为 800x600,质量为 90
  2. 创建对象,将属性(图像)填充为 Base64 字符串
  3. 使用 GSON 序列化对象
  4. 上传字符串

在测试过程中,我在处理图像时遇到错误“内存不足”。我想这就是所有 StackOverflow 提示的地方——这是 BitmapFactory 的一些错误。是的,错误主要出现在调整图像大小时,但它与此操作无关。

当我拍照并处理它们(调整大小等)时 - 堆大小保持在 7-8mb 以下。它只比我通常的应用程序状态多 2-3Mb。

当我将这些图像提交到服务器并且 GSON + Base64 编码器开始发挥作用时 - 它“爆炸”了,我得到了这个:

enter image description here

好吧 - 如您所见 - 在进程完成后,分配的内存按预期减少,但堆大小保持不变。现在,当我拍摄更多照片或使用应用程序执行某些操作时 - 我开始遇到内存不足的错误。

这是我上传 JSON 的代码。关于改进它或处理类似问题的任何建议?也许我可以将 JSON 流式传输到文件中,然后从文件中执行 http 之类的操作?

while (!c.isAfterLast())
{
String data = c.getString(colObjectData);
TrailerInspection trailerInspection = MyGsonWrapper.getMyGson().fromJson(data, TrailerInspection.class);

//Load image data
for (TrailerUnitInspection trailerUnitInspection : trailerInspection.UnitInspections)
{
for (FileContainer fileContainer : trailerUnitInspection.Images)
{
fileContainer.dataFromFile(mContext);
}
}

data = MyGsonWrapper.getMyGson().toJson(trailerInspection);

MyHttpResponse response = processPOST("/trips/" + c.getString(colTripId) + "/trailerinspection", data);

if (response.Code == HttpURLConnection.HTTP_OK)
{
processed.add(c.getString(colGId));
}

c.moveToNext();
}
c.close();

最佳答案

问题是您要在内部存储器中创建并保存准备发送的整个字符串。

String data = MyGsonWrapper.getMyGson().toJson(trailerInspection);

这个字符串可能非常大。您应该将数据分块传输到服务器。
我还没有使用过 gson,但在文档中我发现了类似 JsonWriter 的东西.看看这个类。

更新:

ContentProducer cp = new ContentProducer() {
public void writeTo(OutputStream outstream) throws IOException {
JsonWriter writer = new JsonWriter(new OutputStreamWriter(outstream, "UTF-8"));
// write code here
writer.flush();
}
};
HttpEntity entity = new EntityTemplate(cp);
HttpPost httppost = new HttpPost("http://server.address");
httppost.setEntity(entity);

关于Android:上传图像数量导致堆大小变大 - 如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6636180/

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