在我的控制器中,我调用一个返回promise的服务
var onComplete = function(data) {
$scope.myImage = data;
};
Run Code Online (Sandbox Code Playgroud)
在我的服务中,我通过将url直接传递给图像本身来调用以获取图像:
return $http.get("http://someurl.com/someimagepath")
.then(function(response){
return response.data;
});
Run Code Online (Sandbox Code Playgroud)
所有的调用都成功了,response.data似乎保存在里面的图像中:
????JFIF??;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90
??C
??C
????"??
???}!1AQa"q2???#B??R??$
Run Code Online (Sandbox Code Playgroud)
虽然我不确定它是否确实存在,因为我在显示它时遇到了麻烦.我试过了(在index.html里面)
<img ng-src="{{myImage}}">
and
<img ng-src="{{myImage}}.jpeg">
and
<img ng-src="data:image/JPEG;base64,{{myImage}}">
Run Code Online (Sandbox Code Playgroud)
想法?是否可以从$ http.get返回实际图像并将其响应转换回图像(jpeg等)
谢谢!
par*_*ite 32
这些方法似乎都不完整,这是一个完整的解决方案:
$http({
method: 'GET',
url: imageUrl,
responseType: 'arraybuffer'
}).then(function(response) {
console.log(response);
var str = _arrayBufferToBase64(response.data);
console.log(str);
// str is base64 encoded.
}, function(response) {
console.error('error in getting static img.');
});
function _arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
Run Code Online (Sandbox Code Playgroud)
然后我可以直接使用它:
<img data-ng-src="data:image/png;base64,{{img}}">
Run Code Online (Sandbox Code Playgroud)
将arraybuffer转换为base64的函数直接从ArrayBuffer转换为base64编码的字符串
kor*_*rya 17
以防任何人需要它.
在我的情况下,我必须通过angular的$http服务发送请求,因为各种变形金刚和我们用它做的其他花哨的东西.
因此,基于前面提到的Mozilla指南,我提出了以下解决方案:
let getImageDataURL = (url, imageType = 'image/jpeg') => {
return $http.get(url, {responseType: 'arraybuffer'}).then((res) => {
let blob = new Blob([res.data], {type: imageType});
return (window.URL || window.webkitURL).createObjectURL(blob);
});
};
Run Code Online (Sandbox Code Playgroud)
基本思想是设置responseType底层XHR请求的属性并将二进制内容转换为数据URL.
回来的图像是二进制编码,而不是Base64.
可以理解的是,<img>标签不支持从二进制到属性的源,因此您必须查看另一个解决方案.
您可以尝试使用TypedArrays和btoa函数将二进制编码转换为客户端的Base64 .然后你就可以使用了
<img ng-src="data:image/JPEG;base64,{{myImage}}">
Run Code Online (Sandbox Code Playgroud)
Mozilla的这个指南涵盖了对XHR的请求,并将其直接成像和读取UInt8Array.这应该是一个很好的起点.
它是为普通的旧Javascript编写的,但如果你只是学习绳索,将它翻译成Angular应该是一个很好的练习.
| 归档时间: |
|
| 查看次数: |
34611 次 |
| 最近记录: |