Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
 /*
  * Extract Icon Function - used to extract icons by utilizing the IconLib Library.
  * ----------------------------------------------------------------------------------
  * extractIcon(
  *      From button Boolean Value (bool),
  *      File to extract the Icon from (string)
  * )
  * ----------------------------------------------------------------------------------
  * fromButton suppresses error if it wasn't the users' intention to extract an icon
  * returns: nothing
  */
 private void extractIcon(bool fromButton = false, string iconfile = "")
 {
     if (excomp[0] && iconfile != "")
     {
         dbgmsg("Extracting associated icon to bitmap...");
         (Icon.ExtractAssociatedIcon(iconfile).ToBitmap()).Save(apth + "\\$_bmptmp.bmp");
         MultiIcon conico = new MultiIcon();
         conico.Add("iconinstance").CreateFrom(apth + "\\$_bmptmp.bmp", IconOutputFormat.Vista);
         conico.SelectedIndex = 0;
         conico.Save(apth + "\\$tmp.ico", MultiIconFormat.ICO);
         imgFileIcon.ImageLocation = "$tmp.ico";
         File.Delete(apth + "\\$_bmptmp.bmp");
         dbgmsg("Temporary bitmap file deleted.");
         isicon = true;
     }
     else
     {
         if (fromButton)
         {
             MessageBox.Show("No spoof file imported or Icon Library functions can't be utilized", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
         else
         {
             dbgmsg("Error from un-intended extraction suppressed!");
         }
     }
 }
Exemplo n.º 4
0
 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);
 }
Exemplo 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);
 }
Exemplo n.º 6
0
        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);
        }
        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);
        }
Exemplo n.º 8
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);
        }
Exemplo 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 { }
 }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
0
        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));
        }
Exemplo n.º 12
0
 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);
 }
Exemplo 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 { }
 }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
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);
     }
 }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
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}");
            }
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
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);
                }
            }
        }
Exemplo n.º 20
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);
            }
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
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);
                }
            }
        }
Exemplo n.º 24
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.");
        }
Exemplo n.º 25
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);
            }
        }