Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Converting Icons to Images with a Background Worker

, 25 Oct 2010 CPOL
Using a background worker thread to execute a time consuming task
IconToImage.zip
IconToImage
bin
Debug
IconLib.dll
IconLib.pdb
IconToImage.exe
IconToImage.pdb
IconToImage.vshost.exe
Release
IconLib.dll
IconLib.pdb
IconToImage.exe
IconToImage.pdb
obj
Debug
IconToImage.csproj.GenerateResource.Cache
IconToImage.exe
IconToImage.Form1.resources
IconToImage.pdb
IconToImage.Properties.Resources.resources
Refactor
ResolveAssemblyReference.cache
TempPE
Properties.Resources.Designer.cs.dll
Release
IconToImage.csproj.GenerateResource.Cache
IconToImage.exe
IconToImage.Form1.resources
IconToImage.pdb
IconToImage.Properties.Resources.resources
TempPE
Properties.Resources.Designer.cs.dll
ProgressODoom.dll
Properties
Settings.settings
Resources
folder-open.png
image-x-generic.png
view-refresh.png
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.IconLib;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace IconToImage
{
    public partial class Form1 : Form
    {
        List<string> fileList = new List<string>();
        string initDir = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelectSome_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "icon files (ico, icl)|*.ico;*.icl|executable (dll, exe, ocx,cpl,src)|*.dll;*.exe;*.ocx;*.cpl;*.src";
            if (openFileDialog1.ShowDialog ()== DialogResult.OK )
            {
                lstfileList.Items.Clear(); //clear item list on list box before fill new one
                foreach (string  item in openFileDialog1.FileNames )
                {
                    lstfileList.Items.Add(item); //add item to list
                }
                FileInfo fi = new FileInfo(openFileDialog1.FileName);
                initDir = fi.DirectoryName; //initial folder to creating new folders of converted image
            }
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            rtbReport.Clear(); //clear report
            fileList.Clear(); //clear file list
            foreach (string  item in lstfileList.Items )
            {
                fileList.Add(item); //copy all items in list to the filelist
            }
            //pgbFile.Maximum = fileList.Count;
            pgbFile.Value = 0;
            rtbReport.AppendText("converting in progress...");
            btnConvert.Enabled = false; //disable so that user can't messing around while conversion in progress
            PassedObject objectToPass = new PassedObject(fileList, initDir);
            bgw.RunWorkerAsync(objectToPass); //run with boxed argument
        }
        /// <summary>
        /// object to include in worker argument
        /// </summary>
        public struct PassedObject
        {
            public List<string> fileListing;
            public string initDirectory;
           
            public PassedObject(List<string> listFilenya, string initDirnya)
            {
                fileListing = listFilenya;
                initDirectory = initDirnya;
            }
        }
        /// <summary>
        /// the message to pass when background task want to update te UI
        /// </summary>
        public struct ItemToReport
        {
            public string strToReport ;
            public int id;
            public ItemToReport(string reportString, int ID)
            {
                strToReport = reportString;
                id = ID;
            }
        }

        private void convertIcon(BackgroundWorker worker, DoWorkEventArgs e)
        {
            PassedObject objectToPass = (PassedObject)e.Argument; //perform unboxing
            string initDirectory = objectToPass.initDirectory ; //initial folder to create new folders of converted image
            ///hold list of files
            List<string> fList = objectToPass.fileListing ;
            ///hold maximum icons will be processed
            int maxIcon = new int();
            ///holds many icons has converted
            int curIconProg = new int();
            ///holds many files containing icons has converted
            int curFileProg = new int();
            ///hold maximum files will be converted
            int maxFile = fList.Count;
            foreach (string item in fList )
            {
                FileInfo iconFile = new FileInfo(item);
                ItemToReport pesan = new ItemToReport("processing " + iconFile.Name + "...\n", 0);
                curIconProg = 0; //resetting icon counter, prevent overflow exception at progressbar
                //report : processing----
                worker.ReportProgress(0, pesan);
                //---------------------------
                MultiIcon manyIcon = new MultiIcon();
                manyIcon.Load(item); //load icons from file
                List<SingleIcon> icList = new List<SingleIcon>(manyIcon.Count); //create icon array
                icList.AddRange(manyIcon); //fill icon array
                List<IconImage> iconImageList = new List<IconImage>(); //create image array
                foreach (SingleIcon  iconItem in icList )
                {
                    iconImageList.AddRange (iconItem); //add images from each icon
                    maxIcon = iconImageList.Count * icList.Count;
                    foreach (IconImage  iconImageItem in iconImageList )
                    {
                        if (iconImageItem.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) //only convert 32bit ARGB icons
                        {
                            Directory.CreateDirectory(initDirectory + "\\converted\\" + iconImageItem.Size.Height.ToString() +
                                "x" + iconImageItem.Size.Width.ToString()); //create folder for converted images
                            FileStream iconExtracted = new FileStream(initDirectory + "\\converted\\" + iconImageItem.Size.Height.ToString() + "x" +
                                iconImageItem.Size.Width.ToString() + "\\" + iconFile.Name + iconItem.Name + ".png", FileMode.Create, FileAccess.ReadWrite);  //create stream for saving icon
                            iconImageItem.Transparent.Save(iconExtracted,System.Drawing.Imaging.ImageFormat.Png  ); //store image as png
                            //report icon progress----
                            pesan = new ItemToReport("-->" + iconImageItem.Size.Height.ToString() + "x" + iconImageItem.Size.Width.ToString() +
                                "\\" + iconItem.Name + " has processed\n", 0);
                            worker.ReportProgress(0, pesan);
                            //---------------------------------
                            iconExtracted.Close(); //clear stream. This also unlock the file
                            //curIconProg++; this makes progressbar not full
                        }
                        curIconProg++;
                        //update progress bar-------
                        pesan = new ItemToReport ("",1); //1 berarti prog icon
                        worker.ReportProgress(curIconProg * 100 / maxIcon, pesan);
                        //-----------------------------------
                    }
                }
                curFileProg++;
                //update progressbar---------------
                pesan = new ItemToReport("", 2); //2 berarti prog file
                try
                {
                    worker.ReportProgress(curFileProg * 100 / maxFile, pesan); //prevent divide by zero exception when no file selected
                }
                catch (Exception)
                {
                    
                 //   throw;
                }
                //--------------------------------------------
            }
            //Console.WriteLine("about to end");
        }
        /// <summary>
        /// function for calling background task
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            // Get the BackgroundWorker that raised this event. It's important not to reference directly. Instead, use
            //sender. this works when we have several background worker
            BackgroundWorker worker = sender as BackgroundWorker;
            convertIcon(worker, e);
        }
        /// <summary>
        /// event handler for event that raised when background task want to update the UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ItemToReport report = (ItemToReport)e.UserState; //perform unboxing message
            switch (report.id )
            {
                    //rich text box
                case 0:
                    rtbReport.AppendText(report.strToReport);
                    break;
                    //prog icon
                case 1:
                    pgbIcon.Value = e.ProgressPercentage;
                    
                    break;
                    //prog file
                case 2:
                    pgbFile.Value = e.ProgressPercentage;
                    
                    break;                
            }
        }

        private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnConvert.Enabled = true; 
        }

        private void btnSelectFolder_Click(object sender, EventArgs e)
        {
            
            lstfileList.Items.Clear();
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string item in Directory.GetFiles(folderBrowserDialog1.SelectedPath))
                {
                    FileInfo filename = new FileInfo(item);
                    switch (filename.Extension)
                    {
                        case ".ico":
                        case ".icl":
                        case ".dll":
                        case ".exe":
                        case ".ocx":
                        case ".cpl":
                        case ".src":
                            lstfileList.Items.Add(item);    //menambahkan file yang valid ke dalam list
                            break;
                    }
                }
                initDir = folderBrowserDialog1.SelectedPath;
            }
        }
        
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

asugix
Engineer Donatus Inc.
Indonesia Indonesia
I'm currently a student of Brawijaya University. I work on programming just for hobby. I learn programming since 2nd year of my college. That's when I first bought my PC on year 2004.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411019.1 | Last Updated 25 Oct 2010
Article Copyright 2009 by asugix
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid