I would like to use an Image taken from an Internet address and use it the Icon of one or more Forms in my application.
I don't want to save it on disk. I tried it and had some errors when drawing the bitmap.
So far I have something like this:
internal static Icon DownloadImage(string fromUrl)
{
using (System.Net.WebClient webClient = new System.Net.WebClient())
{
using (Stream stream = webClient.OpenRead(fromUrl))
{
return new Icon(stream);
}
}
}
The last line was originally optimized for images, like this:
return Image.FromStream(stream);
That's where it got tricky and I don't know how to get further.
It's not working in the current state, I want to call it like this:
this.Icon = DownloadImage(url);
Can anyone help me with this?
I am trying to use a .svg
image, but technically it could be any file format.
CodePudding user response:
it is safer to use return Image.FromStream(stream);
so you can refer to any image..
then
Bitmap myBitmap = DownloadImage(url);
IntPtr Hicon = myBitmap.GetHicon();
Icon newIcon = Icon.FromHandle(Hicon);
this.Icon = newIcon;
DestroyIcon(newIcon.Handle);
CodePudding user response:
You can use Image.FromStream() and cast to Bitmap, so you have the GetHicon() method available.
If the Image doesn't need any special treatment, then just return Icon.FromHandle(), passing the value returned by GetHicon()
to the method.
The bool option in FromStream(stream, true)
instructs to preserve ICM information, if present. If it's present, discarding it may compromise the Color definition of the image.
If the image is already transparent, the Icon will preserve the transparency setting.
Remember to call the Dispose()
method (to destroy the handle) of your new Icon when the Form closes or before you replace it with another.
Note: in the question, the SVG format is mentioned. GDI doesn't support this format, as WebP and other more recent formats. See: Using Image Encoders and Decoders in Managed GDI
using System.Drawing;
using System.Net;
internal static Icon GetIconFromWebImage(string fromUrl)
{
using (var client = new WebClient())
using (var stream = client.OpenRead(new Uri(fromUrl)))
using (var img = (Bitmap)Image.FromStream(stream, true)) {
return Icon.FromHandle(img.GetHicon());
}
}
You can the set:
[Some Form].Icon = DownloadImage([some address]);