简体   繁体   中英

How can I use a java string image object in a html img tag - Is it possible?

I am currently generating a javascript image from a base64 string. I am doing something like this

function generateHTML() 
{
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  ......
}

Now I know i can do something like this

document.body.appendChild(image);

but that is not what I want. In my javascript function I am returning back an html string. My question is if it is possible for me to use the javascript image with a html statement like this

<img src=image alt="Mountain View" style="width:304px;height:228px;">

You mean like this, where it uses the img id to append the src?

 function generateHTML() { var picString = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; var image = new Image(); var src = "data:image/jpeg;base64," + picString; document.getElementById('img').src = src; } generateHTML(); 
 <img id="img" alt="Mountain View" title="Red Dot" /> 

If you are looking to get the html string of an element and not looking to append it to the current document, use outerHTML on the Image instance you created.

function generateHTML() {
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  return image.outerHTML;
}

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