在项目里需要在页面中增加一个按钮,然后通过它打开硬盘上的图片,并且保存到相应的目录中。这样,我就建了一个Form,如图所示: 可以看到它有2个Button, 分别是用来打开目录里的图片文件,然后保存到相应的目录中。 另外,我也从控件中拖入了openFileDialog和saveFileDialog这2个控件,其中主要用到了openFileDialog1,saveFileDialog1作为保留。 在当中是一个pictureBox控件,它的SizeMode属性设为Zoom,也就是自动适配原图。 由于需要在调用该Form的时候传入2个值,所以在构造函数中建了2个参数用来传值。 好了,上代码了:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HL_Dev_Template
{
public partial class FormUploadPic : Form
{
private string selectedWp;
private int wpType;
public FormUploadPic(string s, int t)
{
this.selectedWp = s;
this.wpType = t;
InitializeComponent();
initDialog();
}
private void FormUploadPic_Load(object sender, EventArgs e)
{
}
public void initDialog()
{
openFileDialog1.InitialDirectory = @"C:\";//设置起始文件夹
openFileDialog1.Filter = "图片文件 (*.jpg)|*.jpg";
openFileDialog1.FileName = "";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
saveFileDialog1.InitialDirectory = Application.StartupPath + "\\Img\\";
saveFileDialog1.Filter = "图片文件 (*.jpg)|*.jpg";
openFileDialog1.FileName = "文件名";
}
private void button_open_Click(object sender, EventArgs e)
{
}
private void buttonOpenFile_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
pictureBox1.Image = System.Drawing.Image.FromFile(openFileDialog1.FileName);
}
}
private void buttonSaveFile_Click(object sender, EventArgs e)
{
string pictureName = "";
switch (this.wpType)
{
case 1:
pictureName = saveFileDialog1.InitialDirectory + this.selectedWp + "_p.jpg";
break;
case 2:
pictureName = saveFileDialog1.InitialDirectory + this.selectedWp + "_e.jpg";
break;
case 3:
pictureName = saveFileDialog1.InitialDirectory + this.selectedWp + "_s.jpg";
break;
}
using (MemoryStream mem = new MemoryStream())
{
try
{
Bitmap bmp = new Bitmap(pictureBox1.Image);
bmp.Save(@pictureName, pictureBox1.Image.RawFormat);
bmp.Dispose();
MessageBox.Show("图片保存成功!", "注意", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch ( Exception err)
{
MessageBox.Show("图片保存不成功!\r\n" + err.ToString(), "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
}
运行的效果如下图所示: 保存到指定的目录里了。
|