从C#字节数组加载图像,并使用AngularJS将图像放在html标记中
本文关键字:图像 AngularJS html 字节数 字节 数组 加载 | 更新日期: 2023-09-27 18:35:49
我有一个字节数组形式的图像,我正在从以下 C# 方法转换字节数组
public HttpResponseMessage ReturnBytes(byte[] bytes)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(bytes);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
我的 HTML 源代码:
<div ng-app="myApp" ng-controller="myCtrl">
<div id="div_image"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("someurl")
.then(function(response) {
$scope.imageSrc = response.data;
$('.div_image').html('<img src="data:image/png;base64,' + $scope.imageSrc + '" />');
});
});
</script>
我关注的参考链接:
- 如何在 C# 中从 Web API 方法正确获取字节数组?
- 显示 png 图像作为对 jQuery ajax 请求的响应
我无法在 HTML 视图中加载图像。请协助我...
不以
字节数组的形式发送图像,而是Convert.ToBase64String
字节数组并作为文本发送。然后你的代码应该可以工作了。
无需使用 HttpResponseMessage() 方法,只需将字节数组转换为 Base64String 并将其作为 String 类型的响应发送回客户端即可。
C# 源代码:
[HttpPost]
public string GetCalculatorResults()
{
byte[] imgArr = GetImageFromDataBase();
// Here we are converting the byte array to Base64String
return Convert.ToBase64String(imgArr)
}
HTML 和 AngularJS 源代码应该是
<div ng-app="myApp" ng-controller="myCtrl">
<img ng-src="data:image/jpeg;base64,{{ imageSrc }}" />
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.imageSrc = "";
$http.get("someurl")
.then(function(response) {
$scope.imageSrc = response.data;
});
});
</script>
我测试了上面的代码,它运行良好。