如何获取图像数据并存储到隐藏文本框中

时间:2015-02-10 16:58:26

标签: javascript php data-uri

在深入挖掘这个问题很长一段时间之后...我在这里尝试一下......但在此之前让我清楚这里的问题......我在PHP页面中有一个IMG标签,我正在尝试加载图像成功...现在我正在尝试将图像数据捕获到隐藏的文本框中,以便我可以将该图像数据用作mPDF的PHP变量......

为了达到这个目的,我首先制作了Javascript:

function logoImg(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#img_prev').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
        getBase64Image();
    }

    $('.delete-logo').css('display', 'inline-block');
}

function getBase64Image() {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var img = document.getElementById('img_prev');

    context.drawImage(img, 0, 0 );
    var theData = context.getImageData(0, 0, img.width, img.height);

    document.getElementById('tx').value = theData;
}

在PHP文件中,这里是IMG标签:

<div class="logo_prev">
    <img id="img_prev" src="/test7/assets/img/logo-placeholder.png" alt="Your logo" class="img-thumbnail invoice-logo img-responsive"/>
</div>

<br>

<input type='file' onchange="logoImg(this);" name="invoice_logo" class="select-logo" data-validation="mime size" data-validation-allowing="jpg, png, gif" data-validation-max-size="2M" data-validation-error-msg="Only jpg, gif or png are allowed (Max 2mb)" />
<input type="text" id="tx" name="tx"/>

我真的需要一些线索来推进它...请帮助我。

1 个答案:

答案 0 :(得分:0)

您应该使用canvas.toDataURL()方法获取Base64字符串。我已经包含了一个可运行的代码段。

而不是:

var theData = context.getImageData(0, 0, img.width, img.height);

使用此:

var theData = canvas.toDataURL();

function logoImg(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#img_prev').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
        getBase64Image();
    }

    $('.delete-logo').css('display', 'inline-block');
}

function getBase64Image() {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var img = document.getElementById('img_prev');

    context.drawImage(img, 0, 0 );
    var theData = canvas.toDataURL();
    document.getElementById('tx').value = theData;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="logo_prev">
    <img id="img_prev" src="" alt="Your logo" class="img-thumbnail invoice-logo img-responsive"/>
</div>

<br>

<input type='file' onchange="logoImg(this);" name="invoice_logo" class="select-logo" data-validation="mime size" data-validation-allowing="jpg, png, gif" data-validation-max-size="2M" data-validation-error-msg="Only jpg, gif or png are allowed (Max 2mb)" />
<input type="text" id="tx" name="tx"/>