一: 直接把图片放到某个文件夹中
1:<INPUT id="myFile" type="file" class="input" onChange="checkData()" size="34" name="myFile" runat="server">
2:判断过程
<script>
function checkData()
{
var fileName=document.getElementById("myFile").value;
if(fileName=="")
return;
var exName=fileName.substr(fileName.lastIndexOf(".")+1).toUpperCase()
if(exName=="JPG"||exName=="BMP"||exName=="GIF")
{
document.getElementById("myimg").src=fileName
}
else
{
alert("请选择正确的图片文件")
document.getElementById("myFile").value=""
}
}
</script>
<script language="javascript">
window.resizeTo(400,250);
</script>
3:上传图片路径到数据库
private void btnSubmit_Click(object sender, System.EventArgs e)
{
string strImageName="";
string FileName=myFile.Value;
string Publishtime=DateTime.Now.ToString();
string svrid=this.Hidden_svrid.Value.ToString();
string modelid=this.Hidden_modelid.Value.ToString();
string itemid=this.Hidden_itemid.Value.ToString();
string slocal_ip=Request.ServerVariables["REMOTE_HOST"];
string sregtime=System.DateTime.Now.ToString();
string exName=FileName.Substring(FileName.LastIndexOf(".")+1).ToUpper();//截取图片的后缀名
string fn=myFile.PostedFile.FileName;
string imghead=svrid+"_";
string SaveName=imghead+DateTime.Now.ToString("yyyyMMddhhmmssfff");//根据时间生成图片名
strImageName=SaveName+fn.Substring(fn.LastIndexOf("."));//图片名加上图片后缀名
string strpath=Server.MapPath("")+"//upimage//"+"//"+this.Session_UserID+"//";//得到将要保存图片的路径
string saveimg="upimage/"+this.Session_UserID+"/"+strImageName;
string savepath=strpath+strImageName;
string sqlread;
string sqladd;
if(itemid=="")
{
sqlread="select pic_path from BZ_Data_pic where Busi_id='"+this.Session_UserID+"' and Modal_id='"+modelid+"' and svrID='"+svrid+"'";
sqladd="insert into BZ_Data_pic(Modal_id,SvrID,Busi_id,pic_path,Reg_time,Local_ip) values('"+modelid+"','"+svrid+"','"+this.Session_UserID+"','"+saveimg+"','"+sregtime+"','"+slocal_ip+"')";
}
else
{
sqlread="select pic_path from BZ_Data_ModalItemPic where Busi_id='"+this.Session_UserID+"' and Modal_id='"+modelid+"' and Item_ID='"+itemid+"' and svrID='"+svrid+"'";
sqladd="insert into BZ_Data_ModalItemPic(Modal_id,SvrID,Busi_id,Item_ID,pic_path,Reg_time,Local_ip) values('"+modelid+"','"+svrid+"','"+this.Session_UserID+"','"+itemid+"','"+saveimg+"','"+sregtime+"','"+slocal_ip+"')";
}
System.Data.DataTable dt=Framework.ComLib.DataBase.Query(sqlread).Tables[0];
//判断保存的图片张数
if(dt.Rows.Count<3)
{
if(exName=="JPG"||exName=="BMP"||exName=="GIF")
{
if(myFile.PostedFile.ContentLength>204800)//判断图片是否大于200k
{
RegisterClientScriptBlock ("alertInfo","<script>alert('对不起,你上传的图片太大,请转换后上传')</script>");
return;
}
if(System.IO.Directory.Exists(strpath) == false)
{
System.IO.Directory.CreateDirectory(strpath);
}
myFile.PostedFile.SaveAs(savepath);//把图片保存在此路径中
Framework.ComLib.DataBase.ExecuteSql( sqladd);
RegisterClientScriptBlock ("alertInfo","<script>window.opener.location.reload();window.opener.opener=null;window.close();</script>");
}
else
{
RegisterClientScriptBlock ("alertInfo","<script>alert('请选择正确的图片文件')</script>");
return;
}
}
else
{
RegisterClientScriptBlock ("alertInfo","<script>alert('最多只能上传3张图片');location.href=location.href;</script>");
}
}
二: 直接把图片放到数据库仲
一、文件(图片)保存到数据库
//得到用户要上传的文件名
string strFilePathName = loFile.PostedFile.FileName;
string strFileName = Path.GetFileName(strFilePathName);
int FileLength = loFile.PostedFile.ContentLength;
if(FileLength<=0)
return;
try
{//上传文件
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = loFile.PostedFile.InputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);
//建立SQL Server链接
string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
SqlConnection Con = new SqlConnection(strCon);
String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = loFile.PostedFile.ContentType; //记录文件类型
//把其它单表数据记录上传
CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = tbDescription.Text;
//记录文件长度,读取时使用
CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
//跳转页面
Response.Redirect("ShowAll.aspx");
}
catch
{
}
取出来显示:
int ImgID = Convert.ToInt32(Request.QueryString["ID"]); //ID为图片ID
//建立数据库链接
string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
SqlConnection Con = new SqlConnection(strCon);
String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
Con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
SqlReader.Read();
Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
Response.End();
//也可以保存为图像
// FileStream fs = new FileStream(@"C:/aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
// fs.Write((byte[])SqlReader["ImageData"], 0,(int)SqlReader["ImageSize"]);
// fs.Close();
Con.Close();
三 在WinForm环境中把图片放在数据库中
System.Data.SqlClient.SqlCommand cmd = new SqlCommand( " insert imgtable values(@name,@data) " ,conn);
System.Data.SqlClient.SqlParameter pm = new SqlParameter( " @name " ,System.Data.SqlDbType.VarChar, 200 );
pm.Value = fname;
System.Data.SqlClient.SqlParameter pm1 = new SqlParameter( " @data " ,System.Data.SqlDbType.Image);
System.IO.FileStream fs = new System.IO.FileStream(fname,System.IO.FileMode.Open);
int len = ( int )fs.Length;
System.Byte[] fileData = new byte [len];
fs.Read(fileData, 0 ,len);
fs.Close();
pm1.Value = fileData;
cmd.Parameters.Add(pm);
cmd.Parameters.Add(pm1);
conn.Open();
try
... {
cmd.ExecuteNonQuery();
MessageBox.Show("Save Picture to database succeed");
}
catch (System.Exception ex)
... {
MessageBox.Show(ex.ToString());
}
读取的过程
System.Data.SqlClient.SqlCommand cmd = new SqlCommand( " select * from imgtable where imgname like '%bmp%' " ,conn);
conn.Open();
System.Data.SqlClient.SqlDataReader dr;
try
... {
dr = cmd.ExecuteReader();
while(dr.Read())
...{
System.Data.SqlTypes.SqlBinary sb = dr.GetSqlBinary(2);
System.IO.MemoryStream stm = new System.IO.MemoryStream(sb.Value);
System.Drawing.Bitmap bmp = new Bitmap(Bitmap.FromStream(stm));
this.pictureBox1.Image = bmp;
}
dr.Close();
}
catch
... {
}
finally
... {
conn.Close();
}
说明:Sql Server 数据库中 Image/Text这两种数据类型都是容量比较大的数据类型,单字段可以存取2GB的数据,而普通的字段不能超过
8K,Text通常用来保存大文本数据,可直接用字符串判断检索,Image通常用来保存二进制数据,不可直接用字符串判断检索
四 给图片加文字和图片水印
... {
if(UploadFile.PostedFile.FileName.Trim()!="")
...{
//上传文件
string extension = Path.GetExtension(UploadFile.PostedFile.FileName).ToUpper();
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss");
string path = Server.MapPath(".") + "/UploadFile/" + fileName + extension;
UploadFile.PostedFile.SaveAs(path);
//加文字水印,注意,这里的代码和以下加图片水印的代码不能共存
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
Graphics g = Graphics.FromImage(image);
g.DrawImage(image, 0, 0, image.Width, image.Height);
Font f = new Font("Verdana", 32);
Brush b = new SolidBrush(Color.White);
string addText = AddText.Value.Trim();
g.DrawString(addText, f, b, 10, 10);
g.Dispose();
//加图片水印
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile( Server.MapPath(".") + "/Alex.gif");
Graphics g = Graphics.FromImage(image);
g.DrawImage(copyImage, new Rectangle(image.Width-copyImage.Width, image.Height-copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
g.Dispose();
//保存加水印过后的图片,删除原始图片
string newPath = Server.MapPath(".") + "/UploadFile/" + fileName + "_new" + extension;
image.Save(newPath);
image.Dispose();
if(File.Exists(path))
...{
File.Delete(path);
}
Response.Redirect(newPath);
}
}
// 注意:加文字水印和加图片水印的代码不能共存