我试图在angularjs中将图像作为base64字符串发送,但控制器正在转移到错误函数。
angularjs的控制器是这样的
angular.module('app', []).controller('showimageCtrl', showcustomimagecontroller);
showcustomimagecontroller.$inject = ['$scope', '$http'];
function showcustomimagecontroller($scope, $http) {
$http({
url: '/Home/showimage',
method: 'post'
}).then(function (response) {
$scope.image = response.data;
}, function (response) {
alert('error');
});
}
.cshtml视图就像这样
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>textonimage</title>
<script src="~/scripts/jquery-3.1.1.min.js"></script>
<script src="~/scripts/angular.min.js"></script>
<script src="~/app/controller/myimagectrl.js"></script>
</head>
<body ng-app="app">
<div ng-controller="showimageCtrl">
<img width="1000" id="y" src="data:image/png;base64,{{image}}" />
</div>
</body>
</html>
Home控制器中的jsonresult showimage()就像这样
public JsonResult showimage()
{
//creating a image object
System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("/images/DSC06528.JPG")); // set image
//draw the image object using a Graphics object
Graphics graphicsImage = Graphics.FromImage(bitmap);
//Set the alignment based on the coordinates
StringFormat stringformat = new StringFormat();
stringformat.Alignment = StringAlignment.Far;
stringformat.LineAlignment = StringAlignment.Far;
StringFormat stringformat2 = new StringFormat();
stringformat2.Alignment = StringAlignment.Far;
stringformat2.LineAlignment = StringAlignment.Far;
//Set the font color/format/size etc..
Color StringColor = System.Drawing.ColorTranslator.FromHtml("#933eea");//direct color adding
Color StringColor2 = System.Drawing.ColorTranslator.FromHtml("#e80c88");//customise color adding
string Str_TextOnImage = "Happy";//Your Text On Image
string Str_TextOnImage2 = "Onam";//Your Text On Image
graphicsImage.DrawString(Str_TextOnImage, new Font("arial", 400,
FontStyle.Regular), new SolidBrush(StringColor), new Point(3000, 545),
stringformat); Response.ContentType = "image/jpeg";
graphicsImage.DrawString(Str_TextOnImage2, new Font("Edwardian Script ITC", 401,
FontStyle.Bold), new SolidBrush(StringColor2), new Point(4000, 545),
stringformat2); Response.ContentType = "image/jpeg";
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
ImageConverter converter = new ImageConverter();
byte[] j= (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
string base64String = Convert.ToBase64String(j, 0, j.Length);
return Json(base64String);
}
我想让angularjs点击成功功能并显示图像。 提前谢谢。
答案 0 :(得分:1)
我假设response.data
包含图像的base64代码。 (请另外发表评论)
您应该使用ng-src
可能
<img width="1000" id="y" ng-src="data:image/png;base64,{{image}}" />
否则{{image}}
表达式不会与$scope.image
绑定并由Angular评估。
答案 1 :(得分:0)
问题是您将base64编码的图像数据直接作为JSON响应返回。它不是 JSON,不能这样解码,因此你的错误。相反,你应该返回类似的东西:
{ "image": "[base64 encoded data]" }
这将产生一个实际的JSON文档,如:
image
然后,您可以访问响应数据对象的$scope.image = response.data.image;
成员:
r