C#保存图片!2002
保存图片 两种办法,一种字节流存,一种存路径。
大多数人的做法是保存路径,这也是最好的方法。
用字节流操作很繁琐,而且效率不高 。。。
两种方法的优势很明显,如果学习,两个都可以看看 ,如果是项目中肯定选择后者。 给你一个帮助类吧...无论是图黑市文件都可以用:
C# code
namespace add.compents
{
using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
public class UploadHelper {
private UploadHelper() { }
///
/// 判断文件扩展名是否为允许的
///
///
///
//public static bool IsAllowedFileExtension(string fileName) {
// string extsAllowed = Config.AllowedFileExtenstions;
// return Regex.IsMatch(fileName,
// @"^.*[" + extsAllowed + "]$",
// RegexOptions.Compiled |
// RegexOptions.Singleline |
// RegexOptions.IgnoreCase);
//}
///
/// 验证文件名中是否包含不合法字符
///
///
//public static bool IsLegalFileName(string fileName) {
// return Regex.IsMatch(fileName, @"^[a-z|A-Z|0-9|_|\-|\.]*$",
// RegexOptions.Compiled);
//}
///
/// 创建一个随机的文件名
///
///
///
public static string CreateRandomFileName(string exfilename,string
extension) {
Random rnd = new Random((int)DateTime.Now.Ticks);
//Random rnd = new Random();
string rndFileName = rnd.Next(1,100).ToString();
//rndFileName = rndFileName.Substring(0, 6);
//return exfilename + DateTime.Now.ToString("yyyyMMddhhmmss") +
rndFileName + extension;
return exfilename + DateTime.Now.ToString("yyyyMMddhhmmss") +
rndFileName;
}
///
/// Upload a file.
///
///
///
The fileName generated in the server.
///
true/false
///
created by Neil, 2006-1-14
public static bool UploadFile(HttpPostedFile file, string uploadpath,string exfilename,out string saveAsFileName, out string errorMessage) {
string fname = Path.GetFileName(file.FileName);
saveAsFileName = "";
errorMessage = "";
if (fname.Length > 0) {
//bool allowed = IsAllowedFileExtension(fname);
//if (!allowed) {
// errorMessage = "文件的扩展名不符合要求:" + fname;
// return false;
//}
//if (!CheckSize(file,Config.fileSize)) {
// errorMessage = "文件超出规定大小,不能超过
"+Config.fileSize+"K";
// return false;
//}
string extension = fname.Substring(fname.LastIndexOf("."));
saveAsFileName = CreateRandomFileName(exfilename, extension) +
fname;
try {
string path = uploadpath + "\\" + saveAsFileName;
file.SaveAs(path);
} catch (Exception ex) {
errorMessage = "上传文件失败:" + fname;
throw ex;
}
return true;
} else {
errorMessage = "您选择的上传文件不包含有效的文件名。";
return false;
}
}
//public static bool UploadFile1(HttpPostedFile file, out string
saveAsFileName, out string errorMessage)
//{
// string fname = Path.GetFileName(file.FileName);
// saveAsFileName = "";
// errorMessage = "";
// if (fname.Length > 0)
// {
// bool allowed = IsAllowedFileExtension(fname);
// if (!allowed)
// {
// errorMessage = "文件的扩展名不符合要求:" + fname;
// return false;
// }
// if (!CheckSize(file, Config.fileSize))
// {
// errorMessage = "文件超出规定大小,不能超过" + Config.fileSize + "K";
// return false;
// }
// string extension = fname.Substring(fname.LastIndexOf("."));
// saveAsFileName = CreateRandomFileName(extension);
// try
// {
// string path = Config.photoUploadPath + "/" + saveAsFileName;
// file.SaveAs(HttpContext.Current.Server.MapPath(path));
// }
// catch (Exception ex)
// {
// errorMessage = "上传文件失败:" + fname;
// throw ex;
// }
// return true;
// }
// else
// {
// errorMessage = "您选择的上传文件不包含有效的文件名。";
// return false;
// }
//}
private static bool CheckSize(HttpPostedFile file,string filesize) {
return (file.ContentLength <= Convert.ToInt32(filesize)*1024);
/*string fnlower = file.FileName.ToLower();
// 图片小于 200k
if (fnlower.EndsWith(".jpg") || fnlower.EndsWith(".jpeg")) {
} else if (fnlower.EndsWith(".mpg") || fnlower.EndsWith(".mpeg")) {
// 视频小于 2M
return (file.ContentLength <= 2097152);
} else {
return false;
}*/
}
//public static string MakeAvailableFileName(string fileName) {
// string filenamelower = fileName.ToLower();
// string extension =
filenamelower.Substring(filenamelower.LastIndexOf("."));
// string fn = Path.GetFileNameWithoutExtension(fileName);
// string newFileName = fileName;
// int suffix = 1;
// while
(File.Exists(Path.Combine(HttpContext.Current.Server.MapPath(Config.UploadPath),
newFileName))) {
// newFileName = fn + "_" + suffix.ToString() + extension;
// suffix++;
// }
// return newFileName;
//}
//public static void DeleteFile(string fileName)
//{
// string uploadPath = Config.UploadPath;
// string deleteFileName = Path.Combine(uploadPath, fileName);
// try
// {
// if (File.Exists(deleteFileName)) File.Delete(deleteFileName);
// }
// catch
// {
// // silently swallow the exception
// }
//}
}
}
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;
using System.Data.SqlClient;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string inputFile = string.Empty;
static SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=sa");
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.AppendText("");
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "图像文件(*.jpg)|*.jpg|gif文件(*.gif)|*.*|所有文件(*.*)|*.*";
openFileDialog1.Title = "Select a JPG File";
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)------------------------------------选择本地文件
{
richTextBox1.Text = openFileDialog1.FileName;
inputFile = openFileDialog1.FileName;
InsertDB(inputFile);
}
}
private static void InsertDB(string file)
{
FileInfo finfo = new FileInfo(file); //绝对路径
if (finfo.Exists)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Insert into Categories(CategoryName,Picture) values('test',@Content)";
cmd.Parameters.Add("@Content", SqlDbType.Image, (int)finfo.Length, "Image字段名"); //注意,此处参数Size为写
入的字节数
//读取文件
,写入byte数组---------------------------------------------------将文件存入 数据库图片字段
byte[] content = new byte[finfo.Length];
FileStream stream = finfo.OpenRead();
stream.Read(content, 0, content.Length);
stream.Close();
cmd.Parameters["@Content"].Value = content; //为参数赋值
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{ conn.Close();}
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand myCommand = new SqlCommand("Select top 1 Picture from Categories order by CategoryID desc",
conn);
--------------------------------------------------------------------------------从数据库中找到 图片字段
try
{
conn.Open();
SqlDataReader myDataReader;
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (myDataReader.Read())
{
byte[] bin = (byte[])myDataReader["Picture"];
MemoryStream stream = new MemoryStream(bin, true);
stream.Write(bin, 0, bin.Length);
pictureBox1.BackgroundImageLayout = ImageLayout.Center;
pictureBox1.Image = Bitmap.FromStream(stream); ---------------------------------------------------将图片显示在pictureBox
stream.Close();
}
conn.Close(); }
catch (SqlException SQLexc)
{ } } }
}