Javascript画布-将已加载的4波段RGB图像的alpha更改为3波段JPEG图像?

时间:2019-08-09 15:41:17

标签: javascript html canvas png draw

我有一个从服务器加载的图像,其中包含RGB格式的4个波段。由于Alpha波段会导致图像看起来透明,因此我需要裁剪该Alpha波段并将其另存为JPEG格式。我可以想到的一种方法是使用画布,但是,我不确定是否可以进行测试,因为我确实显示图像是相同的。

<p>Image to use:</p>
<img id="scream" src="data/with_alpha.png" alt="The Scream">

<p>Canvas:</p>
<canvas id="myCanvas" width="2400" height="2097" style="border:1px solid #d3d3d3;">
</canvas>


window.onload = function() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  ctx.globalAlpha = 1;
  var img = document.getElementById("scream");
  ctx.drawImage(img, 0, 0);
  // This ones does not do anything to remove the alpha band
  c.toDataURL("image/jpeg", 0.0);
}

1 个答案:

答案 0 :(得分:0)

我从http://sunbox.github.io/image-to-canvas-to-image/找到了答案,可以像这样将画布转换为图像:

        // Get the image
        var sampleImage = document.getElementById("ringoImage"),
            canvas = convertImageToCanvas(sampleImage),
            image = convertCanvasToImage(canvas);  


        // Actions
        document.getElementById("pngHolder").appendChild(image);

        // Converts image to canvas; returns new canvas element
        function convertImageToCanvas(image) {
        var canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            canvas.getContext("2d").drawImage(image, 0, 0);

            return canvas;
        }

        // Converts canvas to an image
        function convertCanvasToImage(canvas) {
            var image = new Image();
            image.src = canvas.toDataURL("image/jpeg");
            return image;
        }