Introduction
Usually in Projects we need some images which are in icon format. Generally we get images in .JPG OR .BMP format. This code snippet when compiled and executed on .Net machine will convert the JP OR BMP file in to .ico format.
The code
Code: .NET
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace iconConvertor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelectSrcImage_Click(object sender, EventArgs e)
{
OpenFileDialog browseFile = new OpenFileDialog();
browseFile.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF";
browseFile.Title = "Select Image file";
if (browseFile.ShowDialog() == DialogResult.Cancel)
return;
try
{
sourceImage.Text = browseFile.FileName;
}
catch (Exception)
{
MessageBox.Show("Error opening file", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
if (sourceImage.Text == "")
MessageBox.Show("Please select an Image file");
Bitmap Cbitmap=null;
try
{
Cbitmap = new Bitmap(sourceImage.Text); //(32, 32, PixelFormat.Format64bppPArgb);
}
catch(Exception)
{
MessageBox.Show("Error opening given Image file", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
Cbitmap.MakeTransparent(Color.White);
System.IntPtr icH = Cbitmap.GetHicon();
Icon ico = Icon.FromHandle(icH);
Cbitmap.Dispose();
System.IO.FileStream f = new System.IO.FileStream(destinationFldr.Text + "\\image.ico", System.IO.FileMode.OpenOrCreate);
ico.Save(f);
MessageBox.Show("Image is converted to ICON and saved in the directory: " + destinationFldr.Text + " with name image.ico");
}
private void btnSelectDestinationFldr_Click(object sender, EventArgs e)
{
FolderBrowserDialog browseFolder = new FolderBrowserDialog();
//browseFolder.Filter = "Directory (/AD)";
if (browseFolder.ShowDialog() == DialogResult.Cancel)
return;
try
{
destinationFldr.Text = browseFolder.SelectedPath;
}
catch (Exception)
{
MessageBox.Show("Error opening file", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void sourceImage_TextChanged(object sender, EventArgs e)
{
}
}
}


