简体   繁体   English

使用角度库将图像转换为base64

[英]Convert image to base64 with the angular library

i have a problem to convert an image to base64 with the library base64 of angularjs. 我在使用angularjs的base64库将图像转换为base64时遇到问题。

see my function : 看我的功能:

var img = new Image();
img.src = conf.storeUrl + '/' +$scope.fRoot.name + $scope.getFileWay() + value.name;
var base64Img = base64.encode(img);

the url of the image is good and the image has been created but the base64Img is empty... i don't understand why.... Some one have a idea ? 图片的网址很好,图片已经创建,但是base64Img为空...我不明白为什么。...有人有想法吗?

thank in advance 预先感谢

Try this: 尝试这个:

/**
 * Convert image 
 * to a base64 data uri
 * @param  {String}   url         
 * @param  {Function} callback    
 * @param  {String}   [outputFormat=image/png]           
 */
function convertImageToDataURI(url, callback, outputFormat) {
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}

Usage 用法

convertImageToDataURI('ImageLink', function(base64Decoded){
    // Base64DataURI
});

Supported input formats 支持的输入格式

image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx
Supported output formats

image/png,image/jpeg,image/webp (chrome)

Demo: 演示:

fiddle 小提琴

Test: toDataUrl mime type 测试:toDataUrl MIME类型

http://kangax.github.io/jstests/toDataUrl_mime_type_test/ http://kangax.github.io/jstests/toDataUrl_mime_type_test/

Browser Support (so far I know) 浏览器支持(到目前为止,我知道)

Images from the local file system 来自本地文件系统的图像

If you want to convert images from the users file system you need to take a different approach. 如果要从用户文件系统转换图像,则需要采用其他方法。 Use the FileReader API (Check out this fiddle ). 使用FileReader API (请参阅此小提琴 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM