How can I show an image in a webBrowser control directly from memory?

How can I show an image in a webBrowser control directly from memory instead of a hard drive? When I use the RAM Disk software to create a virtual disk, you can refer to the image source to load it as follows: img src = "Z: /image.jpg", which Z is a RAM disk. Can this be done in .NET programmatically? or use a memorystream for this?

I would really appreciate some suggestions on this.

+6
source share
1 answer

You can encode an image in base64. for instance

<img src="data:image/gif;base64,MyImageDataEncodedInBase64=" alt="My Image data in base 64" /> 

Here is a complete example of how you can do this:

 using System; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; namespace ImageEncodedInBase64InAWebBrowser { [ComVisible(true)] public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string url = Directory.GetCurrentDirectory() + "\\page.html"; webBrowser1.Url = new Uri(url); webBrowser1.ObjectForScripting = this; } private void button1_Click(object sender, EventArgs e) { string imageInBase64 = ReadImageInBase64(); webBrowser1.Document.InvokeScript("setImageData", new[] { imageInBase64 }); } private string ReadImageInBase64() { string imagePath = Directory.GetCurrentDirectory() + "\\opensource.png"; using (var fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); return Convert.ToBase64String(buffer); } } } } 

And this Javascript code:

 function setImageData(imageBase64) { var myImg = document.getElementById("myImg"); myImg.src = "data:image/png;base64," + imageBase64; } 
+1
source

Source: https://habr.com/ru/post/902070/


All Articles