如何使用javascript将png转换为base64字符串?

时间:2015-02-03 14:36:04

标签: javascript base64

我已经尝试了几种不同的选择,所以很多我都忘记了它们。我正在发出一个AJAX请求,响应是Content-Type: image/png,内容是实际图像。

我绝对喜欢显示图像,但似乎没有任何东西按我想要的方式工作:

// imgdata contains a string that looks like this: "�PNG..."
var img = document.createElement('img');

// no good
img.src = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(data)));

// also no good
img.src = 'data:image/png;base64,' + btoa(encodeURIComponent(data));

// also no good
img.src = 'data:image/png;base64,' + btoa($.map(d, function(x){ return x.charCodeAt(0); }))

我尝试过其他一些东西,但仍然没有骰子。

在Javascript中有没有简单的(甚至是复杂的)方法呢?

2 个答案:

答案 0 :(得分:0)

如果您通过node.js或PHP提供此文件,您可以随时将文件写入服务器临时位置的磁盘,提供服务,然后立即将其删除。

var tempFile = 'path/to/file.jpg';

// Write the file to disk
fs.writeFile(tempFile, base64versionOfPhoto, function (err) {
    if (err) {
        res.header("Content-Type","application/json");
        return res.send(JSON.stringify(err));   
    } else {
        // Pipe the jpg to the user
        res.header("Content-Type","image/jpeg");

        var readStream = fs.createReadStream(tempFile);
        readStream.pipe(res, {end: false});

        readStream.on("end", function () {
            res.end();

            // Delete the file
            fs.unlink(tempFile, function (err) {
                if (err) console.log(err);
            });
        });
    }
});

答案 1 :(得分:0)

这不是base64,而是blob,但你会得到完全相同的结果:

var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200){
            var img = document.getElementById('image');
            var url = window.URL || window.webkitURL;
            img.src = url.createObjectURL(this.response);
        }
    }
    // Relative path because : 
    // No 'Access-Control-Allow-Origin' header is present...
    xhr.open('GET', '/img/logo.png');
    xhr.responseType = 'blob';
    xhr.send();

在此演示:http://jsfiddle.net/sparkup/sp4cukee/

相关问题