简体   繁体   中英

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. 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. 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. 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. 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.

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. And these PNG files are relatively small anyway. About 49KB in size with dimensions of 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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