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

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

问题描述

下面我创建了一个简单的测试用例,显示当img标签的src设置为不同的dataUrls时,它泄漏内存。

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然后,我可以将图像复制到我的画布,所以图像元素完全被bassed,因此否定了设置其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天全站免登陆