C
C#2y ago
duncan3052

❔ supporting .ico files on non-windows platforms

I searched the web for how to convert a .ico file into a bmp or png or basically anything else, but every example I found used System.Drawing libs that are only available on windows. A lot of web pages still use .ico files as favicons as an anachronistic backwards compatibility thing for Internet Explorer. Does anyone know of a way to take a .ico file in memory and convert it to a better supported format?
5 Replies
Angius
Angius2y ago
ImageSharp maybe? If not, just find some ImageMagick wrapper, or even invoke it directly
duncan3052
duncan3052OP2y ago
looking at magick.net, I will post here if it works as a solution
private byte[] ConvertIcoToPng(byte[] bytes)
{
string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".ico");
File.WriteAllBytes(tempFile, bytes);

using MagickImage image = new (tempFile);
image.Format = MagickFormat.Png;
File.Delete(tempFile);
return image.ToByteArray();
}
private byte[] ConvertIcoToPng(byte[] bytes)
{
string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".ico");
File.WriteAllBytes(tempFile, bytes);

using MagickImage image = new (tempFile);
image.Format = MagickFormat.Png;
File.Delete(tempFile);
return image.ToByteArray();
}
duncan3052
duncan3052OP2y ago
Its a pity I have to use a temp file, imagemagick can read a byte array but for some reason it fails in this case. Still this is a nicer and cleaner solution than any I found using the System.Drawing libs. I might use this lib (https://github.com/dlemstra/Magick.NET) for all my image needs in future.
GitHub
GitHub - dlemstra/Magick.NET: The .NET library for ImageMagick
The .NET library for ImageMagick. Contribute to dlemstra/Magick.NET development by creating an account on GitHub.
duncan3052
duncan3052OP2y ago
Thanks for the suggestion. ah I sorted it, ico has no file type identifier at the beginning of the file so without the file suffix imagemagick cant identify what format it is in. The correct code is:
private static byte[] ConvertIcoToPng(byte[] bytes)
{
using MagickImage image = new (bytes, MagickFormat.Ico);
image.Format = MagickFormat.Png;
return image.ToByteArray();
}
private static byte[] ConvertIcoToPng(byte[] bytes)
{
using MagickImage image = new (bytes, MagickFormat.Ico);
image.Format = MagickFormat.Png;
return image.ToByteArray();
}
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server