/// <summary>
/// C#的winform开发图片选择与保存类
/// </summary>
public class HdhCmsImgDoIt
{
public static string path = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf("HdhCms"));//截止到HdhCms目录止
/// <summary>
/// 加载图片
/// </summary>
public static Image LoadImg()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "请选择图片";
ofd.InitialDirectory = Path.GetDirectoryName(ofd.FileName);
ofd.Filter = "(*.jpg/png)|*.jpg;*.png";//只允许.jpg或.png
ofd.Multiselect = false;//true允许上传多张图片
//当用户点击打开时,进入操作逻辑
if (ofd.ShowDialog() == DialogResult.OK)
{
string path = ofd.FileName;
Console.WriteLine(path);
//创建FileStream读取图片流
using (FileStream fileRead = new FileStream(@path, FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] buffer = new byte[fileRead.Length];
fileRead.Read(buffer);
Image i = Image.FromStream(fileRead);
return i;
}
}
else {
return null;
}
}
/// <summary>
/// 保存图片,返回路径
/// </summary>
/// <param name="picbox1"></param>
/// <returns></returns>
public static string SaveImg(PictureBox picbox1)
{
try
{
Bitmap bit = new Bitmap(picbox1.Width, picbox1.Height);
picbox1.DrawToBitmap(bit, picbox1.ClientRectangle);
string fileExt = ".png";
string fileName = DateTime.Now.ToString("mmssffff")+ fileExt; //文件名
string relPath = Path.Combine("Upload", DateTime.Now.ToString("yyMMdd"), fileName); //拼接相对路径
string fullPath = Path.Combine(path, relPath); //拼接绝对路径
string filePath = Path.Combine(path, "Upload", DateTime.Now.ToString("yyMMdd"));//文件路径
if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
bit.Save(fullPath, System.Drawing.Imaging.ImageFormat.Bmp);
MessageBox.Show("上传成功");
return relPath;
}
catch {
MessageBox.Show("上传异常");
return "";
}
}
/// <summary>
/// 默认图片
/// </summary>
public static Image noimg() {
string path2 = "Upload\\noimg.png";
string url = path + path2;
return Image.FromFile(url);
}
}
查看更多关于C#的winform开发图片选择与保存类的详细内容...