public void Convert(Bitmap bitmap, string icoPath) { MultiIcon mIcon = new MultiIcon(); mIcon.Add("Untitled").CreateFrom(bitmap, IconOutputFormat.Vista); mIcon.SelectedIndex = 0; mIcon.Save(icoPath, MultiIconFormat.ICO); }
public static Bitmap ExtractHighResIconImage(string path, int? size = null) { var mi = new MultiIcon(); mi.Load(path); var si = mi.FirstOrDefault(); if (si != null) { IconImage icon; if (size != null) { if (size.Value <= 32) { try { return Icon.ExtractAssociatedIcon(path).ToBitmap(); } catch { } } icon = si.Where(x => x.Size.Height >= size.Value).OrderBy(x => x.Size.Height).FirstOrDefault(); if (icon != null) return icon.Icon.ToBitmap(); } var max = si.Max(_i => _i.Size.Height); icon = si.FirstOrDefault(i => i.Size.Height == max); if(icon != null) return icon.Transparent; } return null; }
public MultiIcon ToIconOverly(string iconAddress) { var multiIcon = new MultiIcon(); var icon = multiIcon.Add("Icon1"); var mainIcon = new MultiIcon(); mainIcon.Load(iconAddress); foreach (var singleIcon in mainIcon[0].Where(image => image.PixelFormat == PixelFormat.Format16bppRgb565 || image.PixelFormat == PixelFormat.Format24bppRgb || image.PixelFormat == PixelFormat.Format32bppArgb) .OrderByDescending( image => image.PixelFormat == PixelFormat.Format16bppRgb565 ? 1 : image.PixelFormat == PixelFormat.Format24bppRgb ? 2 : 3) .ThenByDescending(image => image.Size.Width * image.Size.Height)) { if (!icon.All(i => singleIcon.Size != i.Size || singleIcon.PixelFormat != i.PixelFormat)) { continue; } var bitmap = singleIcon.Icon.ToBitmap(); if (bitmap.PixelFormat != singleIcon.PixelFormat) { var clone = new Bitmap(bitmap.Width, bitmap.Height, singleIcon.PixelFormat); using (var gr = Graphics.FromImage(clone)) { gr.DrawImage(bitmap, new Rectangle(0, 0, clone.Width, clone.Height)); } bitmap.Dispose(); bitmap = clone; } icon.Add(singleIcon.Size.Height * singleIcon.Size.Width < 24 * 24 ? bitmap : ToBitmapOverly(bitmap)); if (singleIcon.Size.Width >= 256 && singleIcon.Size.Height >= 256) { icon[icon.Count - 1].IconImageFormat = IconImageFormat.PNG; } bitmap.Dispose(); } if (icon.Count == 0) { throw new ArgumentException(); } multiIcon.SelectedIndex = 0; return(multiIcon); }
public MultiIcon ToIcon() { var iconSizes = new[] { new Size(256, 256), new Size(64, 64), new Size(48, 48), new Size(32, 32), new Size(24, 24), new Size(16, 16) }; var multiIcon = new MultiIcon(); var icon = multiIcon.Add("Icon1"); foreach (var size in iconSizes) { icon.Add(ToBitmap(size.Width, size.Height)); if (size.Width >= 256 && size.Height >= 256) { icon[icon.Count - 1].IconImageFormat = IconImageFormat.PNG; } } multiIcon.SelectedIndex = 0; return(multiIcon); }
private void NextPic(string path) { if (GlobalSetting.ImageList.Length < 1) { return; } //The image data will load Image im = null; try { //Check if the image is a icon or not if (Path.GetExtension(path).ToLower() == ".ico") { try { MultiIcon mIcon = new MultiIcon(); mIcon.Load(path); //Try to get the largest image of it SingleIcon sIcon = mIcon[0]; IconImage iImage = sIcon.OrderByDescending(ico => ico.Size.Width).ToList()[0]; //Convert to bitmap im = iImage.Icon.ToBitmap(); } catch //If a invalid icon { im = GlobalSetting.ImageList.GetImage(GlobalSetting.CurrentIndex); } } else //If a normal image { im = GlobalSetting.ImageList.GetImage(GlobalSetting.CurrentIndex); var canPlay = ImageAnimator.CanAnimate(im); var isAnime = System.Utility.Helper.File.GetExtension(path).ToLower() == "gif"; if (canPlay && !isAnime) { return; } } GlobalSetting.IsImageError = GlobalSetting.ImageList.imgError; //Show image picturePanel.Zoom = 100; picturePanel.Image = im; } catch//(Exception ex) { picturePanel.Image = null; } if (GlobalSetting.IsImageError) { picturePanel.Image = null; } //Collect system garbage System.GC.Collect(); }
public void CreateIcon(string name,string source, string destination) { MultiIcon icon = new MultiIcon(); SingleIcon single = icon.Add(name); single.CreateFrom(source, IconOutputFormat.FromWinXP); icon.SelectedIndex = 0; icon.Save(destination, MultiIconFormat.ICO); }
public static void Convert(Bitmap bitmap, string icoPath) { var mIcon = new MultiIcon(); mIcon.Add("Untitled").CreateFrom(bitmap, IconOutputFormat.Vista); mIcon.SelectedIndex = 0; mIcon.Save(icoPath, MultiIconFormat.ICO); }
/// <summary> /// Constructs a new <see cref="FileAssociation"/> object containing information about the default program /// associated with the given <paramref name="filePath"/>. /// </summary> /// <param name="filePath"> /// Relative or absolute path to a file (e.g., <c>"C:\some\file.docx"</c>). /// </param> public FileAssociation(string filePath) { FilePath = filePath; ExePath = GetExePath(); AppName = GetAppName(); ProductName = GetProductName(); _multiIcon = GetMultiIcon(); }
protected bool CreateShortcutIcon() { // Skip if a suitable icon file already exists var originalPath = GetShortcutIconPath(); if (File.Exists(originalPath)) { var bytes = new byte[4]; using (var file = File.OpenRead(originalPath)) { file.Read(bytes, 0, 4); } if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 1 && bytes[3] == 0) { return(true); } using (var img = new Bitmap(originalPath)) { var extension = ImageCodecInfo.GetImageDecoders().FirstOrDefault(dec => dec.FormatID == img.RawFormat.Guid)?.FilenameExtension.Replace("*", string.Empty).ToLower().Split(';'); if (extension != null) { if (!extension.Contains(Path.GetExtension(originalPath).ToLower())) { FixWrongIconExtension(originalPath, img); } } } } string gameIconPath = GetGameIconPath(); if (File.Exists(gameIconPath)) { using (Bitmap bitmap = new Bitmap(gameIconPath)) { Size iconSize = new Size(256, 256); using (Bitmap resized = new Bitmap(iconSize.Width, iconSize.Height)) { using (Graphics g = Graphics.FromImage(resized)) { g.DrawImage(bitmap, 0, 0, iconSize.Width, iconSize.Height); } MultiIcon mIcon = new MultiIcon(); SingleIcon sIcon = mIcon.Add("Original"); sIcon.CreateFrom(resized, IconOutputFormat.FromWin95); mIcon.SelectedIndex = 0; mIcon.Save(GetShortcutIconPath(), MultiIconFormat.ICO); #if DEBUG // if (File.Exists(GetGameIconPath())) throw new Exception($"{GetShortcutIconPath()} was not created!"); #endif return(true); } } } return(false); }
public void CreateIcon(string name, string source, string destination) { MultiIcon icon = new MultiIcon(); SingleIcon single = icon.Add(name); single.CreateFrom(source, IconOutputFormat.FromWinXP); icon.SelectedIndex = 0; icon.Save(destination, MultiIconFormat.ICO); }
public static Bitmap ReadIconFile(string path) { MultiIcon mIcon = new MultiIcon(); mIcon.Load(path); //Try to get the largest image of it SingleIcon sIcon = mIcon[0]; IconImage iImage = sIcon.OrderByDescending(ico => ico.Size.Width).ToList()[0]; //Convert to bitmap return iImage.Icon.ToBitmap(); }
/// <summary> /// Returns a Bitmap of the icon associated with exe/dll or loads image file /// </summary> /// <param name="path">Full path to *.exe, *.dll or image file that will be used as the source for new icon</param> /// <returns></returns> public static SingleIcon GetIconFromFile(string path) { MultiIcon mIco = new MultiIcon(); SingleIcon ico = mIco.Add("Icon1"); // Load the image based on file extension switch (Path.GetExtension(path).ToLowerInvariant()) { case ".jpg": case ".jpeg": case ".bmp": case ".png": case ".gif": case ".tiff": ico = ImageToIcon(path); break; case ".exe": case ".dll": case ".ico": try { mIco.Load(path); } // Aseprite's exe produces an exception when trying to get its icon. I don't want to deal with it right now, just ignore it, file will use the default icon catch (System.Drawing.IconLib.Exceptions.InvalidFileException e) { Console.Error.WriteLine(e.Message); } // Should never happen, just a failsafe catch (Exception e) { System.Windows.Forms.MessageBox.Show($"Unexpected error related to an icon, please report it on GitHub!\nLikely you can continue packing prosess despite this error.\n\nError message:\n\n\"{e.Message}\"", "Something went wrong!"); } // If icon pack has multiple icons, take the first one if (mIco.Count > 0) { ico = mIco[0]; } // If exe doesn't have any icon it will not load the 'default' icon // But .NET Icon class can actually extract this 'default exe' icon else if (ico.Count == 0) { ico.CreateFrom(Icon.ExtractAssociatedIcon(path).ToBitmap(), IconOutputFormat.Vista); } // Tip: you have to convert to Bitmap in order to get 16mil colors // if you load directly from icon it gets only 16 colors for some reason break; } return(ico); }
private MultiIcon GetMultiIcon() { if (ExePath == null) { return(null); } var multiIcon = new MultiIcon(); multiIcon.Load(ExePath); return(multiIcon); }
private void ChangeIcon(string file) { try { Icon FileIcon = Icon.ExtractAssociatedIcon(file); MultiIcon MultiIcon = new MultiIcon(); SingleIcon SingleIcon = MultiIcon.Add(Path.GetFileName(file)); SingleIcon.CreateFrom(FileIcon.ToBitmap(), IconOutputFormat.Vista); SingleIcon.Save(Path.GetPathRoot(file) + spreadSettings.WorkDirectory + "\\" + spreadSettings.IconsDirectory + "\\" + Path.GetFileNameWithoutExtension(file.Replace(" ", null)) + ".ico"); } catch { } }
private void btnCreate_Click(object sender, EventArgs e) { MultiIcon multiIcon = new MultiIcon(); multiIcon.Add("Icon 1").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon1.ico")); multiIcon.Add("Icon 2").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon2.ico")); multiIcon.Add("Icon 3").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon3.ico")); multiIcon.Add("Icon 4").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon4.ico")); multiIcon.Add("Icon 5").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon5.ico")); multiIcon.Add("Icon 6").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon6.ico")); multiIcon.Add("Icon 7").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon7.ico")); multiIcon.Save(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"library.icl"), MultiIconFormat.ICL); }
private void btnCreate_Click(object sender, EventArgs e) { MultiIcon multiIcon = new MultiIcon(); multiIcon.Add("Icon 1").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon1.ico")); multiIcon.Add("Icon 2").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon2.ico")); multiIcon.Add("Icon 3").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon3.ico")); multiIcon.Add("Icon 4").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon4.ico")); multiIcon.Add("Icon 5").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon5.ico")); multiIcon.Add("Icon 6").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon6.ico")); multiIcon.Add("Icon 7").Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Icon7.ico")); multiIcon.Save(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "library.icl"), MultiIconFormat.ICL); }
private Icon ConvertToIcon(Bitmap image) { var converted = new MemoryStream(); var multi = new MultiIcon(); var icon = multi.Add("Main"); icon.CreateFrom(image, IconOutputFormat.Vista); multi.SelectedIndex = 0; multi.Save(converted, MultiIconFormat.ICO); converted.Seek(0, SeekOrigin.Begin); return(new Icon(converted)); }
/// <summary> /// Read icon *.ICO file /// </summary> /// <param name="path"></param> /// <returns></returns> public static Bitmap ReadIconFile(string path) { MultiIcon mIcon = new MultiIcon(); mIcon.Load(path); //Try to get the largest image of it SingleIcon sIcon = mIcon[0]; IconImage iImage = sIcon.OrderByDescending(ico => ico.Size.Width).ToList()[0]; //Convert to bitmap return(iImage.Icon.ToBitmap()); }
private void exctractIcon(string path) { try { IconExtractor ie = new IconExtractor(path); Icon icon = ie.GetIcon(0); MultiIcon mIcon = new MultiIcon(); SingleIcon sIcon = mIcon.Add("oink"); Icon[] splitIcons = IconUtil.Split(icon); sIcon.CreateFrom(IconUtil.ToBitmap(splitIcons[splitIcons.Length - 1]), IconOutputFormat.Vista); sIcon.Save(applicationPath + iconName); } catch { } }
public void ChangeIcon(string file) { try { Icon fileIcon = Icon.ExtractAssociatedIcon(file); MultiIcon multiIcon = new MultiIcon(); SingleIcon singleIcon = multiIcon.Add(Path.GetFileName(file)); singleIcon.CreateFrom(fileIcon.ToBitmap(), IconOutputFormat.Vista); singleIcon.Save(Path.GetPathRoot(file) + Settings.WorkDirectory + "\\" + Settings.IconsDirectory + "\\" + Path.GetFileNameWithoutExtension(file.Replace(" ", null)) + ".ico"); } catch (Exception ex) { Debug.WriteLine("ChangeIcon: " + ex.Message); } }
private static SingleIcon ImageToIcon(string imgPath) { Bitmap bmp = (Bitmap)Image.FromFile(imgPath); if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb || bmp.Width > 256 || bmp.Height > 256) { bmp = FixIcon(bmp); } MultiIcon mIco = new MultiIcon(); SingleIcon sIco = mIco.Add("Icon1"); sIco.CreateFrom(bmp, IconOutputFormat.Vista); return(sIco); }
private System.Drawing.Image GetImageFromICO(MemoryStream ms) { System.Drawing.Image theIcon = null; //System.IO.MemoryStream ms = new System.IO.MemoryStream(LoadFile(path)); MultiIcon multiIcon = new MultiIcon(); try { multiIcon.Load(ms); foreach (IconImage iconImage in multiIcon[0]) { MemoryStream msSrc = new MemoryStream(); iconImage.Icon.ToBitmap().Save(msSrc, ImageFormat.Png); if (!iconImage.PixelFormat.ToString().Contains("Indexed")) { System.Drawing.Image imgIco = System.Drawing.Image.FromStream(msSrc); System.Drawing.Image icoImage = new Bitmap(iconImage.Size.Width, iconImage.Size.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(icoImage); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.FillRectangle(System.Drawing.Brushes.White, -1, -1, iconImage.Size.Width + 1, iconImage.Size.Height + 1); g.DrawImage(imgIco, iconImage.Size.Width, iconImage.Size.Height); MemoryStream memStream = new MemoryStream(); imgIco.Save(memStream, System.Drawing.Imaging.ImageFormat.Png); // can output different formats here theIcon = System.Drawing.Image.FromStream(memStream); } else { theIcon = System.Drawing.Image.FromStream(ms); } //break; } } catch { theIcon = System.Drawing.Image.FromStream(ms); } return(theIcon); }
public ResViewer(MultiIcon mIcon) { _MIcon = mIcon; InitializeComponent(); this.Icon = Me.Amon.Properties.Resources.Icon; if (_MIcon != null) { foreach (SingleIcon sIcon in mIcon) { IlIco.Images.Add(sIcon.Name, WIco.GetBitmap(sIcon, 32)); LvIco.Items.Add(new ListViewItem { Text = sIcon.Name, ImageIndex = LvIco.Items.Count }); } } }
static private bool SaveLocalIcon(string localIconPath, Bitmap iconBitmap) { try { MultiIcon bmIcon = new MultiIcon(); SingleIcon bsIcon = bmIcon.Add("Icon 1"); IconOutputFormat outputFormat = IconOutputFormat.None; // Save icon as is bsIcon.CreateFrom(iconBitmap, outputFormat); bsIcon.Save(localIconPath); } catch (Exception e) { return(false); } return(true); }
public Builder LoadIcon() { if (_progId == null) { return(this); } if (_exePath == null) { return(this); } _multiIcon = new MultiIcon(); _multiIcon.Load(_exePath); // Fallback // _icon = Icon.ExtractAssociatedIcon(_exePath); return(this); }
private void buttonConvert_Click(object sender, EventArgs e) { try { MultiIcon mIcon = new MultiIcon(); SingleIcon sIcon = mIcon.Add("Icon1"); string pngPath = textPngPath.Text; string icoPath = textIcoPath.Text; sIcon.CreateFrom(pngPath, IconOutputFormat.FromWinXP); mIcon.SelectedIndex = 0; mIcon.Save(icoPath, MultiIconFormat.ICO); } catch (Exception ex) { alert($"Err={ex}"); } }
public static IconImage GetIconFromFile(string path) { MultiIcon multiIcon = new MultiIcon(); multiIcon.Load(path); SingleIcon singleIcon = multiIcon[0]; List <IconImage> iconImages = new List <IconImage>(); foreach (var item in singleIcon) { iconImages.Add(item); } IconImage iconImage = iconImages.OrderByDescending(x => x.Size.Height).First(); return(iconImage); }
private void btn_Make_Click(object sender, EventArgs e) { using (SaveFileDialog sfd = new SaveFileDialog()) { sfd.FileName = "untitled.ico"; if (sfd.ShowDialog() == DialogResult.OK) { MultiIcon icons = new MultiIcon(); SingleIcon si = icons.Add("pack"); icons.SelectedName = "pack"; foreach (string item in lst_Images.Items) { var newImage = new Bitmap(Bitmap.FromFile(item)); if (newImage.Width > 256 || newImage.Height > 256) { MessageBox.Show($"icon with size larger than 256px width or 256px height cannot be added"); continue; } bool notExist = true; foreach (var ei in si) { if (ei.Size.Width == newImage.Width && ei.Size.Height == newImage.Height) { notExist = false; } } if (notExist) { si.Add(newImage); } else { MessageBox.Show($"icon with same size cannot be added\r\nkeep one of images with size{newImage.Width}*{newImage.Height}"); } } icons.Save(sfd.FileName, MultiIconFormat.ICO); } } }
public unsafe void Save(MultiIcon multiIcon, Stream stream) { if (multiIcon.SelectedIndex == -1) { return; } SingleIcon singleIcon = multiIcon[multiIcon.SelectedIndex]; // ICONDIR header ICONDIR iconDir = ICONDIR.Initalizated; iconDir.idCount = (ushort)singleIcon.Count; iconDir.Write(stream); // ICONENTRIES int entryPos = sizeof(ICONDIR); int imagesPos = sizeof(ICONDIR) + iconDir.idCount * sizeof(ICONDIRENTRY); foreach (IconImage iconImage in singleIcon) { // for some formats We don't know the size until we write, // so we have to write first the image then later the header // IconImage stream.Seek(imagesPos, SeekOrigin.Begin); iconImage.Write(stream); long bytesInRes = stream.Position - imagesPos; // IconDirHeader stream.Seek(entryPos, SeekOrigin.Begin); ICONDIRENTRY iconEntry = iconImage.ICONDIRENTRY; stream.Seek(entryPos, SeekOrigin.Begin); iconEntry.dwImageOffset = (uint)imagesPos; iconEntry.dwBytesInRes = (uint)bytesInRes; iconEntry.Write(stream); entryPos += sizeof(ICONDIRENTRY); imagesPos += (int)bytesInRes; } }
/// <summary> /// Does the preview. /// </summary> /// <param name="selectedFilePath">The selected file path.</param> public void DoPreview(string selectedFilePath) { // Load the icons. try { var multiIcon = new MultiIcon(); multiIcon.Load(selectedFilePath); // Add the icon images. foreach (var iconImage in multiIcon.SelectMany(singleIcon => singleIcon)) iconImages.Add(iconImage); // Add the icons to the control. AddIconsToControl(); } catch { // Maybe we could show something to the user in the preview // window, but for now we'll just ignore any exceptions. } }
private void SaveIcon() { if (_icon == null) { MessageBox.Show(_resourceManager.GetString("NoPathError"), _resourceManager.GetString("Error")); return; } string location = String.Empty; if (_savingLocation == SavingLocation.Desktop) { location = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); location = Path.Combine(location, "Icon" + Guid.NewGuid() + ".ico"); } else if (_savingLocation == SavingLocation.MyLocation) { SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.FileName = "Icon"; saveDlg.DefaultExt = ".ico"; saveDlg.Filter = "Ico files (.ico)|*.ico|Png files (.png)|*.png"; bool?result = saveDlg.ShowDialog(); if (result == true) { location = saveDlg.FileName; } } try { string fName = Guid.NewGuid().ToString(); MultiIcon mIcon = new MultiIcon(); SingleIcon sIcon = mIcon.Add(fName); sIcon.CreateFrom(_icon.ToBitmap(), IconOutputFormat.Vista); sIcon.Save(location); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Returns a Bitmap of the icon associated with exe/dll or loads image file /// </summary> /// <param name="path">Full path to *.exe, *.dll or image file that will be used as the source for new icon</param> /// <returns></returns> public static SingleIcon GetIconFromFile(string path) { MultiIcon mIco = new MultiIcon(); SingleIcon ico = mIco.Add("Icon1"); // Load the image based on file extension switch (Path.GetExtension(path).ToLowerInvariant()) { case ".jpg": case ".jpeg": case ".bmp": case ".png": case ".gif": case ".tiff": ico = ImageToIcon(path); break; case ".exe": case ".dll": case ".ico": mIco.Load(path); // If icon pack has multiple icons, take the first one if (mIco.Count > 0) { ico = mIco[0]; } // If exe doesn't have any icon it will not load the 'default' icon // But .NET Icon class can actually extract this 'default exe' icon else if (ico.Count == 0) { ico.CreateFrom(Icon.ExtractAssociatedIcon(path).ToBitmap(), IconOutputFormat.Vista); } // Tip: you have to convert to Bitmap in order to get 16mil colors // if you load directly from icon it gets only 16 colors for some reason break; } return(ico); }
/// <summary> /// Does the preview. /// </summary> /// <param name="selectedFilePath">The selected file path.</param> public void DoPreview(string selectedFilePath) { // Load the icons. try { var multiIcon = new MultiIcon(); multiIcon.Load(selectedFilePath); // Add the icon images. foreach (var iconImage in multiIcon.SelectMany(singleIcon => singleIcon)) { iconImages.Add(iconImage); } // Add the icons to the control. AddIconsToControl(); } catch { // Maybe we could show something to the user in the preview // window, but for now we'll just ignore any exceptions. } }
public static Bitmap ExtractHighResIconImage(string path, int?size = null) { MultiIcon source1 = new MultiIcon(); string fileName = path; source1.Load(fileName); SingleIcon source2 = source1.FirstOrDefault <SingleIcon>(); if (source2 != null) { if (size.HasValue) { if (size.Value <= 32) { try { return(Icon.ExtractAssociatedIcon(path).ToBitmap()); } catch { } } IconImage iconImage = source2.Where <IconImage>((Func <IconImage, bool>)(x => x.Size.Height >= size.Value)).OrderBy <IconImage, int>((Func <IconImage, int>)(x => x.Size.Height)).FirstOrDefault <IconImage>(); if (iconImage != null) { return(iconImage.Icon.ToBitmap()); } } int max = source2.Max <IconImage>((Func <IconImage, int>)(_i => _i.Size.Height)); IconImage iconImage1 = source2.FirstOrDefault <IconImage>((Func <IconImage, bool>)(i => i.Size.Height == max)); if (iconImage1 != null) { return(iconImage1.Transparent); } } return((Bitmap)null); }
public unsafe void Save(MultiIcon multiIcon, Stream stream) { if (multiIcon.SelectedIndex == -1) return; SingleIcon singleIcon = multiIcon[multiIcon.SelectedIndex]; // ICONDIR header ICONDIR iconDir = ICONDIR.Initalizated; iconDir.idCount = (ushort) singleIcon.Count; iconDir.Write(stream); // ICONENTRIES int entryPos = sizeof(ICONDIR); int imagesPos = sizeof(ICONDIR) + iconDir.idCount * sizeof(ICONDIRENTRY); foreach(IconImage iconImage in singleIcon) { // for some formats We don't know the size until we write, // so we have to write first the image then later the header // IconImage stream.Seek(imagesPos, SeekOrigin.Begin); iconImage.Write(stream); long bytesInRes = stream.Position - imagesPos; // IconDirHeader stream.Seek(entryPos, SeekOrigin.Begin); ICONDIRENTRY iconEntry = iconImage.ICONDIRENTRY; stream.Seek(entryPos, SeekOrigin.Begin); iconEntry.dwImageOffset= (uint) imagesPos; iconEntry.dwBytesInRes = (uint) bytesInRes; iconEntry.Write(stream); entryPos += sizeof(ICONDIRENTRY); imagesPos += (int) bytesInRes; } }
public static Bitmap ExtractHighResIconImage(string path, int?size = null) { var mi = new MultiIcon(); mi.Load(path); var si = mi.FirstOrDefault(); if (si != null) { IconImage icon; if (size != null) { if (size.Value <= 32) { try { return(Icon.ExtractAssociatedIcon(path).ToBitmap()); } catch { } } icon = si.Where(x => x.Size.Height >= size.Value).OrderBy(x => x.Size.Height).FirstOrDefault(); if (icon != null) { return(icon.Icon.ToBitmap()); } } var max = si.Max(_i => _i.Size.Height); icon = si.FirstOrDefault(i => i.Size.Height == max); if (icon != null) { return(icon.Transparent); } } return(null); }
private static void ChangeIconFromBitmap(string pathToTargetExe, Bitmap bmpIcon) { if (bmpIcon.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb || bmpIcon.Width > 256 || bmpIcon.Height > 256) { bmpIcon = FixIcon(bmpIcon); } // Create icon and save it into temp file MultiIcon mIco = new MultiIcon(); SingleIcon sIco = mIco.Add("main"); sIco.CreateFrom(bmpIcon, IconOutputFormat.Vista); string tempIcoPath = System.IO.Path.GetTempFileName(); sIco.Save(tempIcoPath); // Magically inject icon into target exe IconInjector.InjectIcon(pathToTargetExe, tempIcoPath); // Delete temp ico file System.IO.File.Delete(tempIcoPath); }
/// <summary> /// Change image /// </summary> /// <param name="step">Image step to change. Zero is reload the current image.</param> private void NextPic(int step) { picMain.Text = ""; if (GlobalSetting.ImageList.Length < 1) { this.Text = "ImageGlass"; lblInfo.Text = string.Empty; GlobalSetting.IsImageError = true; picMain.Image = null; return; } //Update current index GlobalSetting.CurrentIndex += step; //Check if current index is greater than upper limit if (GlobalSetting.CurrentIndex >= GlobalSetting.ImageList.Length) GlobalSetting.CurrentIndex = 0; //Check if current index is less than lower limit if (GlobalSetting.CurrentIndex < 0) GlobalSetting.CurrentIndex = GlobalSetting.ImageList.Length - 1; //The image data will load Image im = null; try { //Check if the image is a icon or not if (Path.GetExtension(GlobalSetting.ImageList.GetFileName(GlobalSetting.CurrentIndex)).ToLower() == ".ico") { try { MultiIcon mIcon = new MultiIcon(); mIcon.Load(GlobalSetting.ImageList.GetFileName(GlobalSetting.CurrentIndex)); //Try to get the largest image of it SingleIcon sIcon = mIcon[0]; IconImage iImage = sIcon.OrderByDescending(ico => ico.Size.Width).ToList()[0]; //Convert to bitmap im = iImage.Icon.ToBitmap(); } catch //If a invalid icon { im = GlobalSetting.ImageList.GetImage(GlobalSetting.CurrentIndex); } } else //If a normal image { im = GlobalSetting.ImageList.GetImage(GlobalSetting.CurrentIndex); } GlobalSetting.IsImageError = GlobalSetting.ImageList.imgError; //Show image picMain.Image = im; //Zoom condition if(btnZoomLock.Checked) { picMain.Zoom = GlobalSetting.ZoomLockValue; } else { //Reset zoom picMain.ZoomToFit(); } //Get image file information this.UpdateStatusBar(); //Release unused images if (GlobalSetting.CurrentIndex - 1 > -1 && GlobalSetting.CurrentIndex < GlobalSetting.ImageList.Length) { GlobalSetting.ImageList.Unload(GlobalSetting.CurrentIndex - 1); } } catch//(Exception ex) { picMain.Image = null; Application.DoEvents(); if (!File.Exists(GlobalSetting.ImageList.GetFileName(GlobalSetting.CurrentIndex))) { GlobalSetting.ImageList.Unload(GlobalSetting.CurrentIndex); } } if(GlobalSetting.IsImageError) { picMain.Text = GlobalSetting.LangPack.Items["frmMain.picMain._ErrorText"]; picMain.Image = null; } //Select thumbnail item if (GlobalSetting.IsShowThumbnail) { if (thumbBar.Controls.Count > 0) { try { ThumbnailBox tb = (ThumbnailBox)thumbBar.Controls[GlobalSetting.CurrentIndex]; thumbBar.MoveToThumbnail(tb); } catch { } } }//end thumbnail //Collect system garbage System.GC.Collect(); }
private MultiIcon GetMultiIcon() { if (ExePath == null) { return null; } var multiIcon = new MultiIcon(); multiIcon.Load(ExePath); return multiIcon; }
public unsafe void Save(MultiIcon multiIcon, Stream stream) { //Lets prepare the complete file in memory, then we dump everything to a file IMAGE_DOS_HEADER dos_header = new IMAGE_DOS_HEADER(); IMAGE_OS2_HEADER os2_header = new IMAGE_OS2_HEADER(); RESOURCE_TABLE resource_table = new RESOURCE_TABLE(); TYPEINFO rscTypes_Group = new TYPEINFO(); TYPEINFO rscTypes_Icon = new TYPEINFO(); TNAMEINFO[] nameInfos_Group; TNAMEINFO[] nameInfos_Icon; byte[] resourceNames; List<GRPICONDIR> groupIcons = new List<GRPICONDIR>(); Dictionary<ushort, IconImage> icons = new Dictionary<ushort,IconImage>(); int offset = 0; // Lets set the MS DOS header dos_header.e_magic = (int) HeaderSignatures.IMAGE_DOS_SIGNATURE; // MZ dos_header.e_lfanew = 144; // NE Header location. dos_header.e_cblp = 80; dos_header.e_cp = 2; dos_header.e_cparhdr = 4; dos_header.e_lfarlc = 64; dos_header.e_maxalloc = 65535; dos_header.e_minalloc = 15; dos_header.e_sp = 184; offset += (int) dos_header.e_lfanew; // Lets set the NE header os2_header.ne_magic = (int) HeaderSignatures.IMAGE_OS2_SIGNATURE; // NE os2_header.ne_ver = 71; os2_header.ne_rev = 70; os2_header.ne_enttab = 178; os2_header.ne_cbenttab = 10; os2_header.ne_crc = 0; os2_header.ne_flags = 33545; os2_header.ne_autodata = 3; os2_header.ne_heap = 1024; os2_header.ne_stack = 0; os2_header.ne_csip = 65536; os2_header.ne_sssp = 0; os2_header.ne_cseg = 0; // Entries in Segment Table os2_header.ne_cmod = 1; os2_header.ne_cbnrestab = 26; os2_header.ne_segtab = 64; // Offset to Segment Table os2_header.ne_rsrctab = 64; // Offset to Resource Table os2_header.ne_restab = 132;// Later will be overwriten os2_header.ne_modtab = 168; os2_header.ne_imptab = 170; os2_header.ne_nrestab = 332; os2_header.ne_cmovent = 1; os2_header.ne_align = SHIFT_FACTOR; os2_header.ne_cres = 0; os2_header.ne_exetyp = 2; // OS target = Windows. os2_header.ne_flagsothers = 0; os2_header.ne_pretthunks = 0; os2_header.ne_psegrefbytes = 0; os2_header.ne_swaparea = 0; os2_header.ne_expver = 768; // OS version = 300 offset += os2_header.ne_rsrctab; // Resoruce Table resource_table.rscAlignShift = SHIFT_FACTOR; // 9 for now, lets split the entries every 512 bytes; offset += 2; // rscAlignShift // Type Info Groups rscTypes_Group.rtTypeID = 0x8000 + (ushort) ResourceType.RT_GROUP_ICON; rscTypes_Group.rtResourceCount = (ushort) multiIcon.Count; offset += 8; // rtTypeID + rtResourceCount + rtReserved nameInfos_Group = new TNAMEINFO[multiIcon.Count]; offset += sizeof(TNAMEINFO) * multiIcon.Count; // Type Info Icons int iconCounter = 0; foreach(SingleIcon singleIcon in multiIcon) iconCounter += singleIcon.Count; rscTypes_Icon.rtTypeID = 0x8000 + (ushort) ResourceType.RT_ICON; rscTypes_Icon.rtResourceCount = (ushort) iconCounter; offset += 8; // rtTypeID + rtResourceCount + rtReserved nameInfos_Icon = new TNAMEINFO[iconCounter]; offset += sizeof(TNAMEINFO) * iconCounter; resource_table.rscEndTypes = 0; offset += 2; // rscEndTypes // Resource Names os2_header.ne_restab = (ushort) (offset - dos_header.e_lfanew); MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write("ICL"); foreach(SingleIcon singleIcon in multiIcon) bw.Write(singleIcon.Name); resourceNames = new byte[ms.Length]; Array.Copy(ms.GetBuffer(), resourceNames, resourceNames.Length); ms.Dispose(); offset += resourceNames.Length + 1; //resourceNames + rscEndNames // Here is the offset where we are going to start writting the directory int shiftOffset = (offset >> resource_table.rscAlignShift) + 1; // Name Infos Group int iconIndex = 0; for(int i=0; i<multiIcon.Count; i++) { SingleIcon singleIcon = multiIcon[i]; GRPICONDIR groupIconDir = new GRPICONDIR(); groupIconDir.idCount = (ushort) singleIcon.Count; groupIconDir.idType = (ushort) ResourceType.RT_GROUP_ICON; // Name Infos Icons GRPICONDIRENTRY[] goupIconDirEntries = new GRPICONDIRENTRY[singleIcon.Count]; for(int j=0; j<singleIcon.Count; j++) { nameInfos_Icon[iconIndex].rnFlags = (ushort) (ResourceMemoryType.Moveable | ResourceMemoryType.Pure | ResourceMemoryType.Unknown); nameInfos_Icon[iconIndex].rnHandle = 0; nameInfos_Icon[iconIndex].rnID = (ushort) (0x8000 + iconIndex + 1); nameInfos_Icon[iconIndex].rnUsage = 0; nameInfos_Icon[iconIndex].rnOffset = (ushort) shiftOffset; nameInfos_Icon[iconIndex].rnLength = (ushort) Math.Ceiling(singleIcon[j].IconImageSize / (float) (1 << resource_table.rscAlignShift)); shiftOffset += nameInfos_Icon[iconIndex].rnLength; goupIconDirEntries[j] = singleIcon[j].GRPICONDIRENTRY; goupIconDirEntries[j].nID = (ushort) (iconIndex + 1); icons.Add((ushort) (iconIndex + 1), singleIcon[j]); iconIndex++; } nameInfos_Group[i].rnFlags = (ushort) (ResourceMemoryType.Moveable | ResourceMemoryType.Pure | ResourceMemoryType.Unknown); nameInfos_Group[i].rnHandle = 0; nameInfos_Group[i].rnID = (ushort) (0x8000 + i + 1); nameInfos_Group[i].rnUsage = 0; nameInfos_Group[i].rnOffset = (ushort) shiftOffset; nameInfos_Group[i].rnLength = (ushort) Math.Ceiling((6 + singleIcon.Count * sizeof(GRPICONDIRENTRY)) / (float) (1 << resource_table.rscAlignShift)); groupIconDir.idEntries = goupIconDirEntries; groupIcons.Add(groupIconDir); shiftOffset += nameInfos_Group[i].rnLength; } resource_table.rscTypes = new TYPEINFO[2]; resource_table.rscTypes[0] = rscTypes_Group; resource_table.rscTypes[0].rtNameInfo = nameInfos_Group; resource_table.rscTypes[1] = rscTypes_Icon; resource_table.rscTypes[1].rtNameInfo = nameInfos_Icon; resource_table.rscResourceNames = resourceNames; // HERE WE GO TO THE FS... // Lets write the MS DOS header dos_header.Write(stream); // Lets write first Bin segment stream.Write(MSDOS_STUB, 0, MSDOS_STUB.Length); // Lets position over where the "NE" header will be stream.Seek(dos_header.e_lfanew, SeekOrigin.Begin); // Lets write the NE header os2_header.Write(stream); // Lets position over the "Resource Table" stream.Seek(os2_header.ne_rsrctab + dos_header.e_lfanew, SeekOrigin.Begin); // Lets write the "Resource Table" resource_table.Write(stream); // Now write the Icons Directory resource_table.SetGroupIcons(stream, groupIcons); // And the Images... resource_table.SetIcons(stream, icons); }
/// <summary> /// ��ȡͼ����Ϣ /// </summary> /// <param name="path"></param> /// <returns></returns> private static Image[] ReadIcon(String path) { // ����Ϊ���ж� if (String.IsNullOrEmpty(path)) { return null; } // ȡͼ���ļ�·�� int i = 0; int j = path.LastIndexOf(','); if (j > 0) { try { i = int.Parse(path.Substring(j + 1)); } catch (Exception) { i = 0; } path = path.Substring(0, j).Trim(' ', '\'', '"'); } // �ж�ͼ���ļ��Ƿ���� if (!File.Exists(path)) { return null; } // ȡ���ʵ�ͼ�� if (i < 0) { i = 0; } try { // ��ȡͼ����Ϣ MultiIcon mi = new MultiIcon(); mi.Load(path); if (i >= mi.Count) { i = 0; } SingleIcon si = mi[i]; // ȡ��������ߵ�ͼ�� List<Image> img = new List<Image>(); PixelFormat lpf = PixelFormat.Format1bppIndexed; j = si.Count; IconImage icon; while (j > 0) { icon = si[--j]; if (icon.PixelFormat < lpf) { continue; } if (icon.PixelFormat > lpf) { img.Clear(); lpf = icon.PixelFormat; } img.Add(icon.Icon.ToBitmap()); } return img.ToArray(); } catch (Exception) { return null; } }
private WindowsWebBrowser(string exePath, MultiIcon multiIcon) { ExePath = exePath; MultiIcon = multiIcon; }
public Builder LoadIcon() { if (_progId == null) { return this; } if (_exePath == null) { return this; } _multiIcon = new MultiIcon(); _multiIcon.Load(_exePath); // Fallback // _icon = Icon.ExtractAssociatedIcon(_exePath); return this; }
public unsafe void Save(MultiIcon multiIcon, Stream stream) { // LoadLibraryEx only can load files from File System, lets create a tmp file string tmpFile = null; IntPtr hLib = IntPtr.Zero; MemoryStream ms; bool bResult; try { stream.Position = 0; // Find a tmp file where to dump the DLL stream, later we will remove this file tmpFile = Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); byte[] buffer = Resource.EmptyDll; stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); fs.Close(); // Begin the injection process IntPtr updPtr = Win32.BeginUpdateResource(tmpFile, false); if (updPtr == IntPtr.Zero) throw new InvalidFileException(); ushort iconIndex = 1; foreach(SingleIcon singleIcon in multiIcon) { // Lets scan all groups GRPICONDIR grpIconDir = GRPICONDIR.Initalizated; grpIconDir.idCount = (ushort) singleIcon.Count; grpIconDir.idEntries = new GRPICONDIRENTRY[grpIconDir.idCount]; for(int i=0;i<singleIcon.Count; i++) { // Inside every Icon let update every image format IconImage iconImage = singleIcon[i]; grpIconDir.idEntries[i] = iconImage.GRPICONDIRENTRY; grpIconDir.idEntries[i].nID = iconIndex; // Buffer creation with the same size of the icon to optimize write call ms = new MemoryStream((int) grpIconDir.idEntries[i].dwBytesInRes); iconImage.Write(ms); buffer = ms.GetBuffer(); // Update resource but it doesn't write to disk yet bResult = Win32.UpdateResource(updPtr, (int) ResourceType.RT_ICON, iconIndex, 0, buffer, (uint) ms.Length); iconIndex++; // For some reason Windows will fail if there are many calls to update resource and no call to endUpdateResource // It is like there some internal buffer that gets full, after that all calls fail. // This workaround will save the changes every 70 icons, for big files this slow the saving process significantly // but I didn't find a way to make EndUpdateResource works without save frequently if ((iconIndex % 70) == 0) { bResult = Win32.EndUpdateResource(updPtr, false); updPtr = Win32.BeginUpdateResource(tmpFile, false); if (updPtr == IntPtr.Zero) throw new InvalidFileException(); } } // Buffer creation with the same size of the group to optimize write call ms = new MemoryStream(grpIconDir.GroupDirSize); grpIconDir.Write(ms); buffer = ms.GetBuffer(); int id; if (int.TryParse(singleIcon.Name, out id)) { // Write id as an integer bResult = Win32.UpdateResource(updPtr, (int) ResourceType.RT_GROUP_ICON, (IntPtr) id, 0, buffer, (uint) ms.Length); } else { // Write id as string IntPtr pName = Marshal.StringToHGlobalAnsi(singleIcon.Name.ToUpper()); bResult = Win32.UpdateResource(updPtr, (int) ResourceType.RT_GROUP_ICON, pName, 0, buffer, (uint) ms.Length); Marshal.FreeHGlobal(pName); } } // Last call to update the file with the rest not that was not write before bResult = Win32.EndUpdateResource(updPtr, false); // Because Windows Resource functions requiere a filepath, and we need to return an string then lets open // the temporary file and dump it to the stream received as parameter. fs = new FileStream(tmpFile, FileMode.Open, FileAccess.Read); buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, buffer.Length); fs.Close(); } catch(Exception) { throw new InvalidFileException(); } finally { if (hLib != null) Win32.FreeLibrary(hLib); if (tmpFile != null) File.Delete(tmpFile); } }
public unsafe MultiIcon Load(Stream stream) { // LoadLibraryEx only can load files from File System, lets create a tmp file string tmpFile = null; IntPtr hLib = IntPtr.Zero; try { stream.Position = 0; // Find a tmp file where to dump the DLL stream, later we will remove this file tmpFile = Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); fs.Close(); hLib = Win32.LoadLibraryEx(tmpFile, IntPtr.Zero, LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE); if (hLib == IntPtr.Zero) throw new InvalidFileException(); List<string> iconsIDs; lock (typeof(PEFormat)) { mIconsIDs = new List<string>(); bool bResult = Win32.EnumResourceNames(hLib, (IntPtr) ResourceType.RT_GROUP_ICON, new Win32.EnumResNameProc(EnumResNameProc), IntPtr.Zero); if (bResult == false) { // No Resources in this file } iconsIDs = new List<string>(mIconsIDs); } MultiIcon multiIcon = new MultiIcon(); for(int index=0; index<iconsIDs.Count; index++) { string id = iconsIDs[index]; IntPtr hRsrc = IntPtr.Zero; if (Win32.IS_INTRESOURCE(id)) hRsrc = Win32.FindResource(hLib, int.Parse(id), (IntPtr) ResourceType.RT_GROUP_ICON); else hRsrc = Win32.FindResource(hLib, id, (IntPtr) ResourceType.RT_GROUP_ICON); if (hRsrc == IntPtr.Zero) throw new InvalidFileException(); IntPtr hGlobal = Win32.LoadResource(hLib, hRsrc); if (hGlobal == IntPtr.Zero) throw new InvalidFileException(); MEMICONDIR* pDirectory = (MEMICONDIR*) Win32.LockResource(hGlobal); if (pDirectory->wCount != 0) { MEMICONDIRENTRY* pEntry = &(pDirectory->arEntries); SingleIcon singleIcon = new SingleIcon(id); for(int i=0;i<pDirectory->wCount; i++) { IntPtr hIconInfo = Win32.FindResource(hLib, (IntPtr) pEntry[i].wId, (IntPtr) ResourceType.RT_ICON); if (hIconInfo == IntPtr.Zero) throw new InvalidFileException(); IntPtr hIconRes = Win32.LoadResource(hLib, hIconInfo); if (hIconRes == IntPtr.Zero) throw new InvalidFileException(); IntPtr dibBits = Win32.LockResource(hIconRes); if (dibBits == IntPtr.Zero) throw new InvalidFileException(); buffer = new byte[Win32.SizeofResource(hLib, hIconInfo)]; Marshal.Copy(dibBits, buffer, 0, buffer.Length); MemoryStream ms = new MemoryStream(buffer); IconImage iconImage = new IconImage(ms, buffer.Length); singleIcon.Add(iconImage); } multiIcon.Add(singleIcon); } } // If everything went well then lets return the multiIcon. return multiIcon; } catch(Exception) { throw new InvalidFileException(); } finally { if (hLib != null) Win32.FreeLibrary(hLib); if (tmpFile != null) File.Delete(tmpFile); } }
Bitmap GetIcon(IconSize imageSize) { // Attempt to extract the icon from the file if (imageSize == IconSize.Medium) return Icon.ExtractAssociatedIcon(_imagePath).ToBitmap(); MultiIcon multicon = new MultiIcon(); try { multicon.Load(_imagePath); } catch (InvalidFileException ex) { if (Log.IsDebugEnabled) Log.DebugFormat("Failed to get icons from {0}, using default application icon, got exception\n{1}", _imagePath, ex); return Icon.ExtractAssociatedIcon(_imagePath).ToBitmap(); } IconImage largeImage = null; IconImage smallImage = null; if (multicon.Count > 0) { SingleIcon icon = multicon[0]; foreach (IconImage iconImage in icon) { // Ignore low quality icons (they look ugly), really big icons (don't need them that big, saves memory) // or really small ones. if (!IsLowQuality(iconImage) && iconImage.Size.Height <= Huge && iconImage.Size.Height >= Small) { if (largeImage == null) largeImage = iconImage; if (smallImage == null) smallImage = iconImage; if (iconImage.Size.Height > largeImage.Size.Height) largeImage = iconImage; if (iconImage.Size.Height < smallImage.Size.Height) smallImage = iconImage; } } } if (imageSize == IconSize.Small && smallImage != null) return smallImage.Transparent; if (imageSize == IconSize.Large && largeImage != null) return largeImage.Transparent; return Icon.ExtractAssociatedIcon(_imagePath).ToBitmap(); }
public unsafe MultiIcon Load(Stream stream) { // LoadLibraryEx only can load files from File System, lets create a tmp file string tmpFile = null; IntPtr hLib = IntPtr.Zero; try { stream.Position = 0; // Find a tmp file where to dump the DLL stream, later we will remove this file tmpFile = Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); fs.Close(); hLib = Win32.LoadLibraryEx(tmpFile, IntPtr.Zero, LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE); if (hLib == IntPtr.Zero) { throw new InvalidFileException(); } List <string> iconsIDs; lock (typeof(PEFormat)) { mIconsIDs = new List <string>(); bool bResult = Win32.EnumResourceNames(hLib, (IntPtr)ResourceType.RT_GROUP_ICON, new Win32.EnumResNameProc(EnumResNameProc), IntPtr.Zero); if (bResult == false) { // No Resources in this file } iconsIDs = new List <string>(mIconsIDs); } MultiIcon multiIcon = new MultiIcon(); for (int index = 0; index < iconsIDs.Count; index++) { string id = iconsIDs[index]; IntPtr hRsrc = IntPtr.Zero; if (Win32.IS_INTRESOURCE(id)) { hRsrc = Win32.FindResource(hLib, int.Parse(id), (IntPtr)ResourceType.RT_GROUP_ICON); } else { hRsrc = Win32.FindResource(hLib, id, (IntPtr)ResourceType.RT_GROUP_ICON); } if (hRsrc == IntPtr.Zero) { throw new InvalidFileException(); } IntPtr hGlobal = Win32.LoadResource(hLib, hRsrc); if (hGlobal == IntPtr.Zero) { throw new InvalidFileException(); } MEMICONDIR *pDirectory = (MEMICONDIR *)Win32.LockResource(hGlobal); if (pDirectory->wCount != 0) { MEMICONDIRENTRY *pEntry = &(pDirectory->arEntries); SingleIcon singleIcon = new SingleIcon(id); for (int i = 0; i < pDirectory->wCount; i++) { IntPtr hIconInfo = Win32.FindResource(hLib, (IntPtr)pEntry[i].wId, (IntPtr)ResourceType.RT_ICON); if (hIconInfo == IntPtr.Zero) { throw new InvalidFileException(); } IntPtr hIconRes = Win32.LoadResource(hLib, hIconInfo); if (hIconRes == IntPtr.Zero) { throw new InvalidFileException(); } IntPtr dibBits = Win32.LockResource(hIconRes); if (dibBits == IntPtr.Zero) { throw new InvalidFileException(); } buffer = new byte[Win32.SizeofResource(hLib, hIconInfo)]; Marshal.Copy(dibBits, buffer, 0, buffer.Length); MemoryStream ms = new MemoryStream(buffer); IconImage iconImage = new IconImage(ms, buffer.Length); singleIcon.Add(iconImage); } multiIcon.Add(singleIcon); } } // If everything went well then lets return the multiIcon. return(multiIcon); } catch (Exception) { throw new InvalidFileException(); } finally { if (hLib != null) { Win32.FreeLibrary(hLib); } if (tmpFile != null) { File.Delete(tmpFile); } } }
private void WIco_Load(object sender, EventArgs e) { _MIcon = new MultiIcon(); _XmlMenu = new XmlMenu<WIco>(this, null); if (_XmlMenu.Load(Path.Combine(_UserModel.DatHome, EIco.XML_MENU))) { _XmlMenu.GetStrokes("WIco", this); _XmlMenu.GetPopMenu("WIco", CmMenu); _XmlMenu.GetPopMenu("Icl", CmIcl); _XmlMenu.GetPopMenu("Ico", CmIco); } }