HTML5:从画布编码8位灰度JPEG

时间:2013-01-09 10:10:03

标签: javascript html5 html5-canvas jpeg webgl

是否有一种使用Web浏览器客户端技术(html5 / canvas / webgl / javascript)从Canvas编码8位灰度JPEG的简单方法?

我是否可以使用任何现成的JavaScript库而无需任何图像处理知识?浏览器插件不是Flash以外的选项。但如果可以,我不喜欢Flash。

请不要推荐有助于实施这种图书馆的算法或任何链接。

详细信息:实际上,我想使用HTML5文件API读取本地jpeg图像文件,而不是将其转换为8位灰度jpeg,而不是将其上传到服务器。

1 个答案:

答案 0 :(得分:2)

alphaJPEG方法使用两个图像:普通PNG-24和带alpha通道的PNG-24。它生成一个透明的8位JPEG。使用inverse alpha mask代替生成灰度8位JPEG。

<head>
  <style>img[data-alpha-src]{visibility: hidden;}</style>
</head>
<body>
  <img src="image.jpg" data-alpha-src="alpha.png" />
  <!--...-->
  <script src="ajpeg.js"></script>
</body>

ajpeg.js

(function() {

  var create_alpha_jpeg = function(img) {

    var alpha_path = img.getAttribute('data-alpha-src')
    if(!alpha_path) return

    // Hide the original un-alpha'd
    img.style.visiblity = 'hidden'

    // Preload the un-alpha'd image
    var image = document.createElement('img')
    image.src = img.src
    image.onload = function () {

      // Then preload alpha mask
      var alpha = document.createElement('img')
      alpha.src = alpha_path
      alpha.onload = function () {

        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        img.parentNode.replaceChild(canvas, img)

        // For IE7/8
        if(typeof FlashCanvas != 'undefined') FlashCanvas.initElement(canvas)

        // Canvas compositing code
        var context = canvas.getContext('2d')
        context.clearRect(0, 0, image.width, image.height)
        context.drawImage(image, 0, 0, image.width, image.height)
        context.globalCompositeOperation = 'xor'
        context.drawImage(alpha, 0, 0, image.width, image.height)

      }
    }
  }

  // Apply this technique to every image on the page once DOM is ready
  // (I just placed it at the bottom of the page for brevity)
  var imgs = document.getElementsByTagName('img')
  for(var i = 0; i &lt; imgs.length; i++)
    create_alpha_jpeg(imgs[i])

})();

In the head element I linked to FlashCanvas:

<!--[if lte IE 8]><script src="flashcanvas.js"></script><![endif]-->

... and I threw in this to avoid a flicker of the un-alpha’d JPEG:

<强>参考

相关问题