[英]Should ToBase64String() method work with all image types?
I have been using the conversion method ToBase64String for some time now without any issues until now. 我使用转换方法ToBase64String已有一段时间了,到目前为止没有任何问题。 I am basically taking an uploaded image, converting it to a byte array and then using the ToBase64String() method combined with the identified content MIME type to assign to an image tag's source on my page. 我基本上是在获取一个上传的图像,将其转换为字节数组,然后将ToBase64String()方法与已标识的内容MIME类型结合使用,以分配给页面上图像标签的源。 Here is my method: 这是我的方法:
protected string RenderImage(byte[] image, string contentType)
{
try
{
if (profilePhoto != null)
{
byte[] byteArray = image;
string imageBase64 = Convert.ToBase64String(byteArray);
string imageSrc = string.Format("data:"+ contentType +";base64,{0}", imageBase64);
return imageSrc;
}
}
catch (Exception ex)
{
// Catch Exception
}
return null;
}
I am working in the MVC framework so I am assigning the returned value as the source of my image tag within a successful ajax function call. 我在MVC框架中工作,因此我将在成功的Ajax函数调用中将返回值分配为图像标签的源。 A snippet of the code: 一段代码:
success: function (result) {
var newImg = document.getElementById("updatedImage");
newImg.src = result;
}
This has been working fine but lately I've noted that image/png and image/x-png MIME types have not been rendering successfully using this method. 这一直很好,但是最近我注意到使用此方法无法成功渲染image / png和image / x-png MIME类型。 I've compared the attributes of these images with attributes of those which have no problem and I can't find any significant differences that would explain the problem. 我已经将这些图像的属性与没有问题的图像的属性进行了比较,并且找不到任何可以解释该问题的明显差异。
I have also noted that the problem isn't prevalent with JPG files and if I simply assign a direct path to the png file as the source, the file renders appropriately in the image tag. 我还注意到,该问题在JPG文件中并不普遍,如果我只是将直接路径分配给png文件作为源,则该文件会在image标签中适当地呈现。
I seem to have a knack for running into oddities like this but was hoping someone may be able to give some input as to why this may be occurring. 我似乎有遇到这种奇怪情况的诀窍,但我希望有人可以就为什么会发生这种情况提供一些意见。
I would think that the image tag should be able to handle any string provided by the Convert.ToBase64String() method as long as the size of the byte array was within a reasonable limit. 我认为,只要字节数组的大小在合理范围内,image标记就应该能够处理Convert.ToBase64String()方法提供的任何字符串。 And these PNG files are relatively small anyway. 而且这些PNG文件相对较小。 About 49KB in size with dimensions of 232 x 232. 大小约为49KB,尺寸为232 x 232。
How are you getting the image string? 您如何获得图像字符串?
This sounds like a GET size limit issue where the server silently truncates the response. 这听起来像是GET大小限制问题,服务器在其中默默地截断响应。
To troubleshoot this further... I would look at the base64 string you are getting via ajax and compare that to the actual image toBase64 inside your method. 为了进一步解决此问题...我将查看您通过ajax获得的base64字符串,并将其与方法中的实际图像toBase64进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.