将img.src设置为dataUrl会泄漏内存 [英] Setting img.src to dataUrl Leaks Memory

查看:197
本文介绍了将img.src设置为dataUrl会泄漏内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我创建了一个简单的测试用例,显示当img标签的src设置为不同的dataUrls时,会泄漏内存。在src更改为其他内容后,图像数据看起来不会被卸载。

Below I've created a simple test case that shows that when an img tag's src is set to different dataUrls, it leaks memory. It looks like the image data is never unloaded after the src is changed to something else.

<!DOCTYPE html>
<html>
  <head>
    <title>Leak Test</title>
    <script type="text/javascript">
      canvas = null;
      context = null;
      image = null;
      onLoad = function(event)
      {
        canvas = document.getElementById('canvas');
        context = canvas.getContext('2d');
        image = document.getElementById('image');
        setTimeout(processImage, 1000);
      }

      processImage = function(event)
      {
        var imageData = null;
        for (var i = 0; i < 500; i ++)
        {
          context.fillStyle = "rgba(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.random() +")";
          context.fillRect(0, 0, canvas.width, canvas.height);
          imageData = canvas.toDataURL("image/jpeg", .5);
          image.src = imageData;
        }
        setTimeout(processImage, 1000); 
      }
    </script>
  </head>
  <body onload="onLoad(event)">
    <canvas id="canvas"></canvas>
    <img id="image"></img>
  </body>
</html>

如果加载这个html页面,RAM使用情况会随着时间的推移而建立,并且永远不会被清理。此问题看起来非常相似:使用数据URI快速更新图像导致缓存,内存泄漏。有什么可以做的,以防止这种内存泄漏?

If you load this html page, RAM usage builds over time and is never cleaned up. This issue looks very similar: Rapidly updating image with Data URI causes caching, memory leak . Is there anything I can do to prevent this memory leak?

推荐答案

我最后做了一个工作来解决这个问题。只有当image.src更改时才会发生内存膨胀,所以我完全绕过了Image对象。我通过使用dataUrl,将其转换为二进制( https://gist.github.com/borismus/1032746 ) )然后使用jpg.js解析( https://github.com/notmasteryet/jpgjs )。使用jpg.js,我可以将图像复制回我的画布,所以Image元素被完全禁止,因此无需设置其src属性。

I ended up doing a work around for the issue. The memory bloat only happens when the image.src is changed, so I just bypassed the Image object altogether. I did this by taking the dataUrl, converting it into binary (https://gist.github.com/borismus/1032746) then parsing it using jpg.js (https://github.com/notmasteryet/jpgjs). Using jpg.js I can then copy the image back to my canvas, so the Image element is completely bybassed thus negating the need to set its src attribute.

这篇关于将img.src设置为dataUrl会泄漏内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆