PNG圖像轉ICO的方法


    對程序員而言,不給自己寫的程序配個好看的圖標,就好比沒舍得給小閨女花時間扎個辮子一樣,養都養了,就不能養好看些嗎?

可惜photoshop需要插件才能到處ico文件,網上有工具但是用起來還是比較麻煩的,干脆自己寫一個吧!

轉換用的類:

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

namespace IcoMaker
{
public static class HelperIcon
{
private static byte[] pngiconheader =
new byte[] { 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public static Icon PngIconFromImage(Image img, int size = 16)
{
using (Bitmap bmp = new Bitmap(img, new Size(size, size)))
{
byte[] png;
using (System.IO.MemoryStream fs = new System.IO.MemoryStream())
{
bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
fs.Position = 0;
png = fs.ToArray();
}

using (System.IO.MemoryStream fs = new System.IO.MemoryStream())
{
if (size >= 256) size = 0;
pngiconheader[6] = (byte)size;
pngiconheader[7] = (byte)size;
pngiconheader[14] = (byte)(png.Length & 255);
pngiconheader[15] = (byte)(png.Length / 256);
pngiconheader[18] = (byte)(pngiconheader.Length);

fs.Write(pngiconheader, 0, pngiconheader.Length);
fs.Write(png, 0, png.Length);
fs.Position = 0;
return new Icon(fs);
}
}
}
}
}

調用方法:

OpenFileDialog _openDialog = new OpenFileDialog();
//打開圖像類型
_openDialog.Filter = "*.PNG|*.PNG";
_openDialog.Multiselect = false;
_openDialog.ShowDialog();
if (_openDialog.FileName != "")
{
//將打開的圖片存入Bitmap中
System.Drawing.Bitmap bmpIco = new System.Drawing.Bitmap(_openDialog.FileName);

SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "圖標(*.ico)|*.ico";
dlg.CheckPathExists = true;
dlg.ShowDialog();
if (!string.IsNullOrEmpty(dlg.FileName))
{
System.IO.FileStream fs = new System.IO.FileStream(dlg.FileName, System.IO.FileMode.Create);
System.Drawing.Icon icon = HelperIcon.PngIconFromImage(bmpIco, 64);

//將Icon保存的指定的輸出
icon.Save(fs);
fs.Close();
MessageBox.Show("圖標生成成功!");
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM