从Base64转换图像时出错 - HTMLImageElement已损坏

时间:2015-03-08 22:56:29

标签: javascript php html html5

我尝试加载图像并通过PHP将其转换为二进制数据,然后解码数据并通过Javascript将其加载到HTML5画布上。但是我遇到了以下错误:

Uncaught InvalidStateError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.

这是我的所有代码,PHP的唯一内容就是预先。请注意我也尝试使用btoa方法。我试图找到解决问题的方法时,在stackoverflow上找到了hexToBase64方法。

<?php
    $image_data = file_get_contents('test.png');
    $encoded_image = base64_encode($image_data);
    $btoa = "hexToBase64('" . $encoded_image . "')";
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Experimental Reader</title>
    </head>

    <body>
        <canvas id="reader" width="100%" height="100%">Whoah, your browser is old! You need to update it to use our reader.</canvas>
    </body>

    <script>
        window.onload = function() {
            var canvas  = document.getElementById("reader");
            var ctx     = canvas.getContext("2d");
            var image   = document.createElement('img');
            image.src='data:image/png;base64,' + <?php echo $btoa; ?>;
            ctx.drawImage(image, 0, 0);
        }

        function hexToBase64(str) {
            return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
        }
    </script>
</html>

1 个答案:

答案 0 :(得分:0)

您的代码应如下所示:

<?php
    $image_data = file_get_contents('test.png');
    $encoded_image = base64_encode($image_data);
    $btoa = "hexToBase64('" . $encoded_image . "')";
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Experimental Reader</title>
    </head>

    <body>
        <canvas id="reader" width="100%" height="100%">Whoah, your browser is old! You need to update it to use our reader.</canvas>
    </body>

    <script>
        var canvas;

        window.onload = function() {
            canvas       = document.getElementById("reader");
            var image    = document.createElement('img');
            image.onload = imageLoaded;
            image.src='data:image/png;base64,' + <?php echo $btoa; ?>;
        }

        function hexToBase64(str) {
            return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
        }

        function imageLoaded(evnt) {
            //after successful image loading we can draw it
            var ctx     = canvas.getContext("2d");
            ctx.drawImage(evnt.target, 0, 0);
        }
    </script>
</html>