在一个img src标签上显示不同格式的普通图像,以及base64图像

Display on one img src tag normal images on different formats, and base64 images

本文关键字:图像 格式 以及 base64 显示 一个 img 标签 src      更新时间:2023-09-26

我使用javascript来显示HTML上的图像,base64编码来自WS。在少数情况下,我得到png, gif, jpg格式的图像,并希望在相同的<img src= >标签中显示它们。

$("#testImage").append("<img src='"data:image/png;base64," +imgSRC+"">);

其中imgSRC为base64图像。

1。我如何使用一个<img src>标签来显示base64图像,并在同一img src标签上显示正常图像?或者改变这个标签,当我现在返回imgSRCjpg/png…的形象。例如,当我得到一个关于图像的返回值,如果它是base64或正常:append("<img src='"data:image/png;base64," +checkImageFormat(imgSRC)+"">);

我怎么能通过checkImageFormat(imgSRC)的结果改变当前对象的img src标签?

我建议将"data:image/png;base64"部分也存储在数据库中(或任何来源)。这样你就不用检查了。

另一个解决方案可能是:

$(function(){
    var $img = $('<img/>')
                   .attr({ src: 'data:image/png;base64,' + imgSrc })
                   .error(function(){
                        $(this).attr({ src: imgSrc }); 
                        //If we end up here the image couldn't be loaded 
                        //If so, we assume that its a jpeg/png/gif
                    });
    $("#testImage").append($img);
});