Ejemplo n.º 1
0
        public unsafe MultiIcon Load(Stream stream)
        {
            stream.Position = 0;
            SingleIcon singleIcon = new SingleIcon("Untitled");
            ICONDIR iconDir = new ICONDIR(stream);
            if (iconDir.idReserved != 0)
                throw new InvalidMultiIconFileException();

            if (iconDir.idType != 1)
                throw new InvalidMultiIconFileException();

            int entryOffset = sizeof(ICONDIR);

            // Add Icon Images one by one to the new entry created
            for(int i=0; i<iconDir.idCount; i++)
            {
                stream.Seek(entryOffset, SeekOrigin.Begin);
                ICONDIRENTRY entry = new ICONDIRENTRY(stream);

                // If there is missing information in the header... lets try to calculate it
                entry = CheckAndRepairEntry(entry);

                stream.Seek(entry.dwImageOffset, SeekOrigin.Begin);

                singleIcon.Add(new IconImage(stream, (int) (stream.Length - stream.Position)));
                entryOffset += sizeof(ICONDIRENTRY);
            }

            return new MultiIcon(singleIcon);
        }
Ejemplo n.º 2
0
        public unsafe MultiIcon Load(Stream stream)
        {
            stream.Position = 0;
            SingleIcon singleIcon = new SingleIcon("Untitled");
            ICONDIR    iconDir    = new ICONDIR(stream);

            if (iconDir.idReserved != 0)
            {
                throw new InvalidMultiIconFileException();
            }

            if (iconDir.idType != 1)
            {
                throw new InvalidMultiIconFileException();
            }

            int entryOffset = sizeof(ICONDIR);

            // Add Icon Images one by one to the new entry created
            for (int i = 0; i < iconDir.idCount; i++)
            {
                stream.Seek(entryOffset, SeekOrigin.Begin);
                ICONDIRENTRY entry = new ICONDIRENTRY(stream);

                // If there is missing information in the header... lets try to calculate it
                entry = CheckAndRepairEntry(entry);

                stream.Seek(entry.dwImageOffset, SeekOrigin.Begin);

                singleIcon.Add(new IconImage(stream, (int)(stream.Length - stream.Position)));
                entryOffset += sizeof(ICONDIRENTRY);
            }

            return(new MultiIcon(singleIcon));
        }
Ejemplo n.º 3
0
        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();
        }
Ejemplo n.º 4
0
            internal Enumerator(SingleIcon list)
            {
                mList  = list;
                mIndex = 0;
#if !WinCopies3
                Current = null;
#endif
            }
Ejemplo n.º 5
0
        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);
        }
        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);
        }
Ejemplo n.º 7
0
        private void GetInfo(FileInfo fi)
        {
            Name             = fi.Name;
            Size             = fi.Length;
            Hidden           = (FileAttributes.Hidden & fi.Attributes) > 0 ? true : false;
            CreatedTime      = fi.CreationTimeUtc;
            LastAccessTime   = fi.LastAccessTimeUtc;
            LastModifiedTime = fi.LastWriteTimeUtc;

            if (Extension.ToLower() == ".exe" || Extension.ToLower() == ".ttf" || Extension.ToLower() == ".ico")
            {
                int index = CommVar.sil_l.IconIndex(fi.FullName, false);

                SystemImageList.SHGetFileInfo(
                    Extension,
                    FILE_ATTRIBUTE_NORMAL,
                    ref shfi,
                    shfiSize,
                    (uint)dwFlags);

                if (shfi.iIcon == index)
                {
                    return;
                }
                else
                {
                    thisIconIndex = index;
                }

                Path = fi.FullName;
                CommVar.mi.Clear();
                SingleIcon singleIcon = CommVar.mi.Add("Untitled");
                if (CommVar.IsVista)
                {
                    singleIcon.Add(CommVar.sil_v.Icon(IconIndex));
                }
                singleIcon.Add(CommVar.sil_x.Icon(IconIndex));
                singleIcon.Add(CommVar.sil_l.Icon(IconIndex));
                singleIcon.Add(CommVar.sil_s.Icon(IconIndex));

                CommVar.mi.SelectedIndex = 0;
                CommVar.mi.Save(CommVar.TempFolder + @"\temp.ico", MultiIconFormat.ICO);
                FileStream fs =
                    new FileStream(CommVar.TempFolder + @"\temp.ico", FileMode.Open,
                                   FileAccess.Read, FileShare.None);

                byte[] fbs = new byte[fs.Length];
                fs.Read(fbs, 0, (int)fs.Length);
                fs.Close();
                fs.Dispose();
                IconData = fbs;
                File.Delete(CommVar.TempFolder + @"\temp.ico");
                Path = "";
            }
        }
Ejemplo n.º 8
0
        /// <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);
        }
Ejemplo n.º 9
0
 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 { }
 }
Ejemplo n.º 10
0
        private static void InjectIcon(string pathToTargetExe, SingleIcon icon)
        {
            // Save icon to a temp file
            string tempIcoPath = Path.GetTempFileName();

            icon.Save(tempIcoPath);

            // Magically inject icon into the target exe
            IconInjector.InjectIcon(pathToTargetExe, tempIcoPath);

            // Delete temp ico file
            File.Delete(tempIcoPath);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Replaces icon of the target exe with the new one
        /// </summary>
        /// <param name="pathToTargetExe">Full path to the executable, the icon of which will be replaced</param>
        /// <param name="pathToFileWithIcon">Full path to *.exe, *.dll or image file that will be used as the source for new icon</param>
        public static void ChangeIcon(string pathToTargetExe, string pathToFileWithIcon)
        {
            // Load the image based on file extension
            SingleIcon ico = GetIconFromFile(pathToFileWithIcon);

            // If icon is empty
            if (ico.Count == 0)
            {
                return;
            }

            InjectIcon(pathToTargetExe, ico);
        }
Ejemplo n.º 12
0
        /// <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());
        }
Ejemplo n.º 13
0
 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 { }
 }
Ejemplo n.º 14
0
 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);
     }
 }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 16
0
        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}");
            }
        }
Ejemplo n.º 17
0
 private void Export_Click(object sender, EventArgs e)
 {
     if (Icons.SelectedItems.Count > 0 && SaveTo.ShowDialog() == DialogResult.OK)
     {   // Collect all checked items from the Export menu and parse into an array of width x length sizes.
         var sizes = Array.ConvertAll(Choices(ExportAs.DropDownItems),
                                      item => Parse(item.Text.Replace("&", string.Empty).ToLowerInvariant().Trim()));
         foreach (ListViewItem selection in Icons.SelectedItems)
         {
             SingleIcon icon = (new MultiIcon()).Add(selection.Text);
             foreach (var size in sizes)
             {
                 icon.Add(imageMso[selection.Text, size[0], size[1]]);
             }
             icon.Save(Path.Combine(SaveTo.SelectedPath, string.Format("{0}.{1}", selection.Text, "ico")));
             DestroyIcon(icon.Icon.Handle);
         }
         MessageBox.Show("Export Complete.", "Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Ejemplo n.º 18
0
        private void DoSelect()
        {
            if (_MIcon != null)
            {
                if (LvIco.SelectedItems.Count < 1)
                {
                    return;
                }
                ListViewItem item = LvIco.SelectedItems[0];
                if (item.Index > -1 && item.Index < _MIcon.Count)
                {
                    SelectedIcon = _MIcon[item.Index];
                }

                DialogResult = DialogResult.OK;
            }

            Close();
        }
Ejemplo n.º 19
0
        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);
        }
Ejemplo n.º 20
0
        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);
        }
Ejemplo n.º 21
0
        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;
            }
        }
Ejemplo n.º 22
0
        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);
                }
            }
        }
Ejemplo n.º 23
0
        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);
            }
        }
Ejemplo n.º 24
0
 private void Save_Click(object sender, EventArgs e)
 {
     if (Icons.SelectedItems.Count > 0 && SaveTo.ShowDialog() == DialogResult.OK)
     {   // Collect all checked items from the Save menu and parse into an array of image formats.
         var formats = Array.ConvertAll(Choices(SaveAs.DropDownItems), item => Format(item.Name));
         var size    = Parse(Pixels.Text.ToLowerInvariant().Trim());
         foreach (ListViewItem selection in Icons.SelectedItems)
         {
             using (var image = imageMso[selection.Text, size[0], size[1]])
                 using (var canvas = new Bitmap(size[0], size[1]))
                     using (var drawing = Graphics.FromImage(canvas))
                     { // Image is drawn on a colored opaque canvas for formats that do not support transparency.
                         drawing.Clear(Palette.Color);
                         drawing.DrawImage(image, 0, 0);
                         foreach (ImageFormat format in formats)
                         {
                             string filename = Path.Combine(SaveTo.SelectedPath,
                                                            string.Format("{0}.{1}", selection.Text, Extension(format)));
                             if (format == ImageFormat.Icon)
                             { // image.Save(filename, format); // Loses color depth. Use IconLib instead.
                                 SingleIcon icon = (new MultiIcon()).Add(selection.Text);
                                 icon.Add(image);
                                 icon.Save(filename);
                                 DestroyIcon(icon.Icon.Handle);
                             }
                             else if (format == ImageFormat.Bmp || format == ImageFormat.Gif || format == ImageFormat.Jpeg)
                             {
                                 canvas.Save(filename, format); // These formats do not support alpha channel transparency.
                             }
                             else
                             {
                                 image.Save(filename, format);
                             }
                         }
                     }
         }
         MessageBox.Show("Save Complete.", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Ejemplo n.º 25
0
        /// <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);
        }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
0
        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);
        }
Ejemplo n.º 28
0
        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);
        }
Ejemplo n.º 29
0
        public MultiIcon Load(Stream stream)
        {
            stream.Position = 0;
            //Lets read the MS DOS header
            IMAGE_DOS_HEADER dos_header = new IMAGE_DOS_HEADER(stream);
            if (dos_header.e_magic != (int) HeaderSignatures.IMAGE_DOS_SIGNATURE) //MZ
                throw new InvalidICLFileException();

            //Lets position over the "NE" header
            stream.Seek(dos_header.e_lfanew, SeekOrigin.Begin);

            //Lets read the NE header
            IMAGE_OS2_HEADER os2_header = new IMAGE_OS2_HEADER(stream);
            if (os2_header.ne_magic != (int) HeaderSignatures.IMAGE_OS2_SIGNATURE) //NE
                throw new InvalidICLFileException();

            //Lets position over the "Resource Table"
            stream.Seek(os2_header.ne_rsrctab + dos_header.e_lfanew, SeekOrigin.Begin);

            //Resource Table doesn't contain ICON resources
            if (os2_header.ne_restab == os2_header.ne_rsrctab)
                return new MultiIcon();

            //Lets read the Resource Table
            RESOURCE_TABLE                  resource_table  = new RESOURCE_TABLE(stream);
            Dictionary<ushort, IconImage>   icons           = resource_table.GetIcons(stream);
            List<GRPICONDIR>                groupIcons      = resource_table.GetGroupIcons(stream);
            List<string>                    groupNames      = new List<string>(resource_table.ResourceNames);
            if (groupNames[0].ToLower() == "icl")
                groupNames.RemoveAt(0);

            SingleIcon[] singleIcons = new SingleIcon[groupIcons.Count];
            for(int i=0; i<singleIcons.Length; i++)
            {
                if (i < groupNames.Count)
                    singleIcons[i] = new SingleIcon(groupNames[i]);
                else
                {
                    string freeName = FindFreeName(groupNames);
                    groupNames.Add(freeName);
                    singleIcons[i] = new SingleIcon(freeName);
                }

                foreach(GRPICONDIRENTRY iconEntry in groupIcons[i].idEntries)
                    singleIcons[i].Add(icons[iconEntry.nID]);
            }

            // If everything went well then lets create the multiIcon.
            return new MultiIcon(singleIcons);
        }
Ejemplo n.º 30
0
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: IcoPngCombine.exe [start_folder]");
                Console.WriteLine("Start folder should contain this directory/file structure:");
                Console.WriteLine("    size\\category\\icon_name.png");
                Console.WriteLine("Like you can see in this repo: https://github.com/KDE/oxygen-icons");
                Console.WriteLine("This tool creates a \"results\" folder in the start folder and puts all of the combined icons there");

                return;
            }

            string startFolder = args[0];

            if (!Directory.Exists(startFolder))
            {
                Console.Error.WriteLine($"Directory {startFolder} doesn't exist.");

                return;
            }

            string results = Path.Combine(startFolder, "results");

            Directory.CreateDirectory(results);

            string[] sizes = Directory.GetDirectories(startFolder);

            HashSet <string> createdIcons = new HashSet <string>();

            foreach (string scannedSize in sizes)
            {
                string[] categories = Directory.GetDirectories(scannedSize);
                foreach (string category in categories)
                {
                    string catName = Path.GetFileName(category);

                    string[] icons = Directory.GetFiles(category, "*.png");
                    foreach (string icon in icons)
                    {
                        string iconFileName = Path.GetFileName(icon);
                        string iconName     = Path.GetFileNameWithoutExtension(icon);

                        string iconFullPath = Path.Combine(catName, iconFileName);
                        string iconId       = Path.Combine(catName, iconName);

                        if (createdIcons.Contains(iconId))
                        {
                            continue;
                        }

                        createdIcons.Add(iconId);

                        MultiIcon     img = new MultiIcon();
                        int           index = -1, selectedIndex = -1, selectedIndexSize = 0;
                        List <string> szs = new List <string>();
                        foreach (string sz in sizes)
                        {
                            string fullPath = Path.Combine(sz, iconFullPath);
                            if (!File.Exists(fullPath))
                            {
                                continue;
                            }

                            string sizeName = Path.GetFileName(sz);

                            SingleIcon ic = img.Add(sizeName);

                            try
                            {
                                Bitmap bmp = (Bitmap)Bitmap.FromFile(fullPath);

                                try
                                {
                                    ic.CreateFrom(bmp, IconOutputFormat.Vista);

                                    szs.Add(sizeName);

                                    index += 1;
                                    if (!Int32.TryParse(new String(sizeName.TakeWhile(c => c >= '0' && c <= '9').ToArray()), out int size))
                                    {
                                        size = 0;
                                    }

                                    if (selectedIndex < 0 || selectedIndexSize < size)
                                    {
                                        selectedIndex     = index;
                                        selectedIndexSize = size;
                                    }
                                }
                                catch (ImageTooBigException)
                                {
                                    Console.WriteLine($"Image {sizeName}\\{iconId} has dimensions that are too big: w={bmp.Width}, h={bmp.Height}");

                                    img.Remove(ic);
                                }
                            }
                            catch (InvalidPixelFormatException ex)
                            {
                                Console.WriteLine($"Ignoring size {sizeName} of {iconId} because {ex.Message}, required is {PixelFormat.Format32bppArgb}");

                                img.Remove(ic);
                            }
                        }

                        if (selectedIndex < 0)
                        {
                            continue;
                        }

                        string dirName = Path.Combine(results, catName);
                        if (!Directory.Exists(dirName))
                        {
                            Directory.CreateDirectory(dirName);
                        }

                        img.SelectedIndex = selectedIndex;

                        Console.WriteLine($"Saving {iconId} with sizes [{String.Join(", ", szs)}]");

                        string icoName = Path.Combine(results, iconId) + ".ico";
                        img.Save(icoName, MultiIconFormat.ICO);
                    }
                }
            }

            Console.WriteLine($"Done. Created {createdIcons.Count} icons.");
        }
Ejemplo n.º 31
0
Archivo: AIco.cs Proyecto: burstas/rmps
        public static Image GetBitmap(SingleIcon sIcon, int dim)
        {
            IconImage img = sIcon[0];
            int max = img.Image.Width;
            int tmp;
            for (int i = 1; i < sIcon.Count; i += 1)
            {
                if (img.PixelFormat < sIcon[i].PixelFormat)
                {
                    img = sIcon[i];
                    max = img.Image.Width;
                    continue;
                }

                tmp = sIcon[i].Image.Width;
                tmp = tmp > dim ? tmp - dim : dim - tmp;
                if (tmp < max)
                {
                    max = tmp;
                    img = sIcon[i];
                    continue;
                }
            }

            Image bmp = img.Icon.ToBitmap();
            if (bmp.Width != dim)
            {
                bmp = BeanUtil.ScaleImage(bmp, dim, true);
            }
            return bmp;
        }
Ejemplo n.º 32
0
        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);
            }
        }
Ejemplo n.º 33
0
        public MultiIcon Load(Stream stream)
        {
            stream.Position = 0;
            //Lets read the MS DOS header
            IMAGE_DOS_HEADER dos_header = new IMAGE_DOS_HEADER(stream);

            if (dos_header.e_magic != (int)HeaderSignatures.IMAGE_DOS_SIGNATURE)  //MZ
            {
                throw new InvalidICLFileException();
            }

            //Lets position over the "NE" header
            stream.Seek(dos_header.e_lfanew, SeekOrigin.Begin);

            //Lets read the NE header
            IMAGE_OS2_HEADER os2_header = new IMAGE_OS2_HEADER(stream);

            if (os2_header.ne_magic != (int)HeaderSignatures.IMAGE_OS2_SIGNATURE)  //NE
            {
                throw new InvalidICLFileException();
            }

            //Lets position over the "Resource Table"
            stream.Seek(os2_header.ne_rsrctab + dos_header.e_lfanew, SeekOrigin.Begin);

            //Resource Table doesn't contain ICON resources
            if (os2_header.ne_restab == os2_header.ne_rsrctab)
            {
                return(new MultiIcon());
            }

            //Lets read the Resource Table
            RESOURCE_TABLE resource_table        = new RESOURCE_TABLE(stream);
            Dictionary <ushort, IconImage> icons = resource_table.GetIcons(stream);
            List <GRPICONDIR> groupIcons         = resource_table.GetGroupIcons(stream);
            List <string>     groupNames         = new List <string>(resource_table.ResourceNames);

            if (groupNames[0].ToLower() == "icl")
            {
                groupNames.RemoveAt(0);
            }

            SingleIcon[] singleIcons = new SingleIcon[groupIcons.Count];
            for (int i = 0; i < singleIcons.Length; i++)
            {
                if (i < groupNames.Count)
                {
                    singleIcons[i] = new SingleIcon(groupNames[i]);
                }
                else
                {
                    string freeName = FindFreeName(groupNames);
                    groupNames.Add(freeName);
                    singleIcons[i] = new SingleIcon(freeName);
                }

                foreach (GRPICONDIRENTRY iconEntry in groupIcons[i].idEntries)
                {
                    singleIcons[i].Add(icons[iconEntry.nID]);
                }
            }

            // If everything went well then lets create the multiIcon.
            return(new MultiIcon(singleIcons));
        }
Ejemplo n.º 34
0
        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());
        }
Ejemplo n.º 35
0
        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);
                }
            }
        }
Ejemplo n.º 36
0
Archivo: AIco.cs Proyecto: burstas/rmps
        private void AddTab(string msg, SingleIcon ico)
        {
            _TpCnt += 1;

            TabPage page = new TabPage();
            page.TabIndex = _TpCnt;
            page.Text = msg;
            //page.UseVisualStyleBackColor = true;
            TcIco.TabPages.Add(page);

            IcoEditor editor = new IcoEditor(this);
            editor.InitOnce();
            editor.Dock = DockStyle.Fill;
            editor.SingleIcon = ico;
            page.Controls.Add(editor);

            TcIco.SelectedTab = page;
            _IIco = editor;
        }