slimCODE

commUNITY
Welcome to slimCODE Sign in | Join | Help
in Search

slimCODE, aka Martin Plante

Convert ICO to PNG

I was looking for a free and simple application to convert icon files containing multiple resolutions, to multiple PNG files. I'm sure there must be such an application out there, but the few I checked were too complicated for my needs. I did what too many programmers do: I reinvented the wheel. Turns out it was very simple. I did a minimally featured console application, who's code looks like this:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace ConvertIcons
{
  class Program
  {
    static void Main( string[] arguments )
    {
      try
      {
        if( arguments.Length == 0 )
          throw new ArgumentException( "No icon filename provided." );

        // Default values
        int minSize = 1;
        int maxSize = 256;
        int stepSize = 1;
        string filename = null;

        foreach( string argument in arguments )
        {
          if( argument.StartsWith( "-min", StringComparison.InvariantCultureIgnoreCase ) )
          {
            if( !int.TryParse( argument.Substring( 2 ), out minSize ) )
              throw new ArgumentException( "Invalid minimum size argument." );

            if( ( minSize < 1 ) || ( minSize > 512 ) )
              throw new ArgumentException( "The minimum size must be a value from 1 to 512." );
          }
          else if( argument.StartsWith( "-max", StringComparison.InvariantCultureIgnoreCase ) )
          {
            if( !int.TryParse( argument.Substring( 2 ), out maxSize ) )
              throw new ArgumentException( "Invalid maximum size argument." );

            if( ( maxSize < 1 ) || ( maxSize > 512 ) )
              throw new ArgumentException( "The maximum size must be a value from 1 to 512." );
          }
          else if( argument.StartsWith( "-step", StringComparison.InvariantCultureIgnoreCase ) )
          {
            if( !int.TryParse( argument.Substring( 2 ), out stepSize ) )
              throw new ArgumentException( "Invalid step size argument." );

            if( ( stepSize < 1 ) || ( stepSize > 512 ) )
              throw new ArgumentException( "The step size must be a value from 1 to the maximum size." );
          }
          else
          {
            if( filename != null )
              throw new ArgumentException( "Too many parameters." );

            filename = argument;
          }
        }

        if( minSize > maxSize )
          throw new ArgumentException( "The minimum size cannot be greater than the maximum size." );

        if( filename == null )
          throw new ArgumentException( "No icon filename provided." );

        Program.GenerateImages( minSize, maxSize, stepSize, filename );
      }
      catch( ArgumentException except )
      {
        Console.WriteLine( except.Message );
        Program.DisplayUsage();
      }
      catch( Exception except )
      {
        Console.WriteLine( except.Message );
      }
    }

    private static void DisplayUsage()
    {
      Console.WriteLine( "ConvertIcons [-min###] [-max###] [-step###] icon_filename" );
      Console.WriteLine( "  where -min indicates the minimum image size to generate (default = 1)" );
      Console.WriteLine( "        -max indicates the maximum image size to generate (default = 256)" );
      Console.WriteLine( "        -step indicates the step of each size to generate (default = 1)" );
      Console.WriteLine();
      Console.WriteLine( "This application extracts multiple icons from a single icon file, and generates multiple PNG files." );
      Console.WriteLine();
      Console.WriteLine( "For example, to extract the 16x16, 32x32 and 48x48 icons from file 'foo.ico', use:" );
      Console.WriteLine( "ConvertIcons -min16 -max48 -step16 foo.ico" );
      Console.WriteLine();
      Console.WriteLine( "This will generate files foo16.png, foo32.png and foo48.png, if those resolutions are found." );
    }

    private static void GenerateImages( int minSize, int maxSize, int stepSize, string filename )
    {
      string baseFilename = System.IO.Path.Combine(
        System.IO.Path.GetDirectoryName( filename ),
        System.IO.Path.GetFileNameWithoutExtension( filename ) );

      for( int size = minSize; size <= maxSize; size += stepSize )
      {
        try
        {
          Icon icon = new Icon( filename, new Size( size, size ) );

          if( ( icon.Width == size ) && ( icon.Height == size ) )
          {
            Bitmap bitmap = icon.ToBitmap();
            string newFilename = baseFilename + size.ToString() + ".png";

            bitmap.Save( newFilename );

            Console.WriteLine( "Generated {0}x{0} image named {1}", size, newFilename );
          }
        }
        catch( Exception except )
        {
          Console.WriteLine( "Error generating {0}x{0} image: {1}", size, except.Message );
        }
      }
    }
  }
}

Should I build a binary?

 

Tags: , ,
Published Friday, September 28, 2007 6:39 PM by slimcode
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Some guy said:

Thanks! Nice and simple.

January 28, 2008 1:12 PM
 

Scott Bleasdell said:

I found a bug (well, technically 3).  In your foreach (string argument in arguments) loop you are trying to get the min, max, and step values from the parameters specified.  However, your substring values are wrong.  Your substring values should be 4 for min, 4 for max, and 5 for step.

June 20, 2008 3:41 PM
 

Scott Bleasdell said:

I loved this post.  Thank you so much for posting this for me.  I did, however, need to make some changes to make it work better specifically for me.  I think that you, or others, might find my changes useful too so here they are:

I added support for automatic detection of whether the icon file is a folder or a file.  If a folder, the code now loops through the folder and converts all the icons in that folder.

Enjoy!!!

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Text;

namespace ConvertIcons

{

   class Program

   {

       private static int minSize = 1;

       private static int maxSize = 256;

       private static int stepSize = 1;

       static void Main(string[] arguments)

       {

           try

           {

               if (arguments.Length == 0)

                   throw new ArgumentException("No icon filename provided.");

               // Default values

               string filename = null;

               foreach (string argument in arguments)

               {

                   if (argument.StartsWith("-min", StringComparison.InvariantCultureIgnoreCase))

                   {

                       if (!int.TryParse(argument.Substring(4), out minSize))

                           throw new ArgumentException("Invalid minimum size argument.");

                       if ((minSize < 1) || (minSize > 512))

                           throw new ArgumentException("The minimum size must be a value from 1 to 512.");

                   }

                   else if (argument.StartsWith("-max", StringComparison.InvariantCultureIgnoreCase))

                   {

                       if (!int.TryParse(argument.Substring(4), out maxSize))

                           throw new ArgumentException("Invalid maximum size argument.");

                       if ((maxSize < 1) || (maxSize > 512))

                           throw new ArgumentException("The maximum size must be a value from 1 to 512.");

                   }

                   else if (argument.StartsWith("-step", StringComparison.InvariantCultureIgnoreCase))

                   {

                       if (!int.TryParse(argument.Substring(5), out stepSize))

                           throw new ArgumentException("Invalid step size argument.");

                       if ((stepSize < 1) || (stepSize > 512))

                           throw new ArgumentException("The step size must be a value from 1 to the maximum size.");

                   }

                   else

                   {

                       if (filename != null)

                           throw new ArgumentException("Too many parameters.");

                       filename = argument;

                   }

               }

               if (minSize > maxSize)

                   throw new ArgumentException("The minimum size cannot be greater than the maximum size.");

               if (filename == null)

                   throw new ArgumentException("No icon filename provided.");

               Program.GenerateImages(minSize, maxSize, stepSize, filename);

           }

           catch (ArgumentException except)

           {

               Console.WriteLine(except.Message);

               Program.DisplayUsage();

           }

           catch (Exception except)

           {

               Console.WriteLine(except.Message);

           }

       }

       private static void DisplayUsage()

       {

           Console.WriteLine("ConvertIcons [-min###] [-max###] [-step###] icon_filename");

           Console.WriteLine("  where -min indicates the minimum image size to generate (default = 1)");

           Console.WriteLine("        -max indicates the maximum image size to generate (default = 256)");

           Console.WriteLine("        -step indicates the step of each size to generate (default = 1)");

           Console.WriteLine();

           Console.WriteLine("This application extracts multiple icons from a single icon file, and generates multiple PNG files.");

           Console.WriteLine();

           Console.WriteLine("For example, to extract the 16x16, 32x32 and 48x48 icons from file 'foo.ico', use:");

           Console.WriteLine("ConvertIcons -min16 -max48 -step16 foo.ico");

           Console.WriteLine();

           Console.WriteLine("This will generate files foo16.png, foo32.png and foo48.png, if those resolutions are found.");

       }

       private static void GenerateImages(int minSize, int maxSize, int stepSize, string filename)

       {

           // Determine whether the user supplied a folder or a file

           // Try a folder first

           bool isFile = false;

           System.IO.DirectoryInfo folder = null;

           System.IO.FileInfo file;

           try

           {

               folder = new System.IO.DirectoryInfo(filename);

               if (!folder.Exists)

                   throw new Exception();

           }

           catch

           {

               // Not a folder

               // See if it is a value file

               try

               {

                   file = new System.IO.FileInfo(filename);

                   if (!file.Exists)

                       throw new Exception();

                   else

                       isFile = true;

               }

               catch

               {

                   throw new System.IO.FileNotFoundException("Cannot file file/folder " + filename);

               }

           }

           if (isFile)

               CreatePNGs(filename);

           else    //Must be a folder

           {

               foreach (System.IO.FileInfo file2 in folder.GetFiles("*.ico", System.IO.SearchOption.TopDirectoryOnly))

                   CreatePNGs(System.IO.Path.Combine(file2.DirectoryName, file2.Name));

           }

       }

       private static void CreatePNGs(string filename)

       {

           string baseFilename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), System.IO.Path.GetFileNameWithoutExtension(filename));

           for (int size = minSize; size <= maxSize; size += stepSize)

           {

               try

               {

                   Icon icon = new Icon(filename, new Size(size, size));

                   if ((icon.Width == size) && (icon.Height == size))

                   {

                       Bitmap bitmap = icon.ToBitmap();

                       string newFilename = baseFilename + size.ToString() + ".png";

                       bitmap.Save(newFilename);

                       Console.WriteLine("Generated {0}x{0} image named {1}", size, newFilename);

                   }

               }

               catch (Exception except)

               {

                   Console.WriteLine("Error generating {0}x{0} image: {1}", size, except.Message);

               }

           }

       }

   }

}

June 20, 2008 4:08 PM
 

Lin said:

Great, very helpful!

Thanks!

October 6, 2008 10:18 AM

Leave a Comment

(required) 
(optional)
(required) 
Submit