1,目的:
2,知识点:
- 转换成图标图像(ico)时,需要获取图像句柄,然后根据句柄生成Ico图像,否则生成的图像不能作为应用的图标使用。
IntPtr hwd = bitmap.GetHicon();
Icon icon = Icon.FromHandle(hwd);
icon.Save(fs);
- 利用反射获取系统可支持的图片类型,获取静态属性的值。
ImageFormat format = typeof(ImageFormat).GetProperty(comboBox1.Text).GetValue(null) as ImageFormat;
3,效果展示:
4,代码:
public partial class Form1 : Form
{
string useExt;
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
using(OpenFileDialog ofd=new OpenFileDialog())
{
ofd.Multiselect = false;
if (useExt != null)
{
ofd.Filter = useExt;
}
if(ofd.ShowDialog()== DialogResult.OK)
{
txtFilePath.Text = ofd.FileName;
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
using(SaveFileDialog sfd=new SaveFileDialog())
{
sfd.CheckPathExists = true;
string ext=comboBox1.Text;
if (comboBox1.Text.ToUpper() == "JPEG")
{
ext = "jpg";
}
if (comboBox1.Text.ToUpper() == "ICON")
{
ext = "ico";
}
sfd.Filter = $"*.{ext}文件|*.{ext}";
if(sfd.ShowDialog()== DialogResult.OK)
{
txtSavePath.Text = sfd.FileName;
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtFilePath.Text)|| string.IsNullOrEmpty(txtSavePath.Text))
{
MessageBox.Show("请先选择文件路径","提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string sizeStr = comboBox2.Text;
string[] wandh = sizeStr.Split('*');
double width,height;
if (wandh.Length == 2)
{
if(double.TryParse(wandh[0],out width) && double.TryParse(wandh[1],out height))
{
Image img = Image.FromFile(txtFilePath.Text);
Size size ;
if ((width ==1)&& (height == 1))
{
size = new Size(img.Width, img.Height);
}
else
{
size = new Size((int)width, (int)height);
}
Bitmap bitmap = new Bitmap(img,size);
ImageFormat format = typeof(ImageFormat).GetProperty(comboBox1.Text).GetValue(null) as ImageFormat;
using(FileStream fs=new FileStream(txtSavePath.Text, FileMode.Create))
{
if (format == ImageFormat.Icon)
{
IntPtr hwd = bitmap.GetHicon();
Icon icon = Icon.FromHandle(hwd);
icon.Save(fs);
}
else
{
bitmap.Save(fs, format);
}
}
MessageBox.Show("已保存至:"+txtSavePath.Text,"提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("目标尺寸参数格式异常", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("目标尺寸参数数量异常", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
List<string> list = new List<string>();
//获取所有可供转换的类型
foreach (var item in typeof(ImageFormat).GetProperties())
{
comboBox1.Items.Add(item.Name);
list.Add($"*.{item.Name}文件|*.{item.Name}");
}
list.Add("*.jpg文件|*.jpg");
list.Reverse();
useExt = string.Join("|", list);
if (comboBox1.Items.Count > 0)
comboBox1.SelectedIndex = comboBox1.Items.Count-1;
comboBox2.SelectedIndex = 0;
}
}