How do I get a C# WebBrowser control to show jpeg files (raw)?

时间秒杀一切 提交于 2019-11-27 14:53:15

You have to implement an async pluggable protocol, e.g. IClassFactory, IInternetProtocol... Then you use CoInternetGetSession to register your protocol. When IE calls your implementation, you can serve your image data from memory/provide mime type.

It's a bit tedious, but doable. Look at IInternetProtocol and pluggable protocols documentation on MSDN.

You cannot do it. You cannot stuff images into Microsoft's web-browser control.

The limitation comes from the IWebBrowser control itself, which .NET wraps up.

If you want a total hack, try having your stream be the HTML file that only shows your picture. You lose your image byte stream and will have to write the image to disk.

I do not know whether the WebBrowser .NET control supports this, but RFC2397 defines how to use inline images. Using this and a XHTML snippet created on-the-fly, you could possibly assign the image without the need to write it to a file.

Image someImage = Image.FromFile("mypic.jpg");

// Firstly, get the image as a base64 encoded string
ImageConverter imageConverter = new ImageConverter();
byte[] buffer = (byte[])imageConverter.ConvertTo(someImage, typeof(byte[]));
string base64 = Convert.ToBase64String(buffer, Base64FormattingOptions.InsertLineBreaks);

// Then, dynamically create some XHTML for this (as this is just a sample, minimalistic XHTML :D)
string html = "<img src=\"data:image/" . someImage.RawFormat.ToString() . ";base64, " . $base64 . "\">";

// And put it into some stream
using (StreamWriter streamWriter = new StreamWriter(new MemoryStream()))
{
    streamWriter.Write(html);
    streamWriter.Flush();
    webBrowser.DocumentStream = streamWriter.BaseStream;
    webBrowser.DocumentType = "text/html";
}

No idea whether this solution is elegant, but I guess it is not. My excuse for not being sure is that it is late at night. :)

References:

IE only support 32KB for inline images in base64 encoding, so not a good solution.

Tim Ludwinski

Try the res: protocol.

I haven't tried it with a .net dll but this post says it should work. Even if it does require a C++ dll it's much simpler to use as far as coding goes.

I've created a post that show you how here that shows you how to create the resource script and use the res: protocol correctly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!