上传图片的相对路径到数据库教程中相应字段里,读取显示时,将控件(假设用的是image控件)的imageurl属性指向该相对路径即可。
code:
protected void button1_click(object sender, eventargs e)
{
string name = fileupload1.filename;//获取文件名
string type = name.substring(name.lastindexof(".") + 1);
//获取文件类型
string ipath = server.mappath("image") + "" + name;
//获取文件路径
string wpath = "image" + name;
//[color=red]设置文件保存相对路径
(这里的路径起始就是我们存放图片的文件夹名)[/color]
string query1 = "insert into images values
('" + wpath + "')";
if (type == "jpg" || type == "gif" ||
type == "bmp" || type == "png")
{
fileupload1.saveas(ipath); //服务器保存路径
sqlhelper.execternonquery(query1);
}
}
显示按钮事件:
code:
protected void button2_click(object sender, eventargs e)
{
string query2 = "select * from images where
image_id=" + convert.toint32(textbox1.text);
sqldatareader sdr = sqlhelper.getreader(query2);
string wpath2 = "";
while (sdr.read())
{
wpath2 = sdr[1].tostring();
//获得相对路径
}
sdr.close();
image1.imageurl = wpath2;
//图片显示路径就是相对路径
label1.text = wpath2; //显示相对路径
}
下面看另一个实例
后台:
protected void button1_click(object sender, eventargs e)
{
upimagefile(fileupload1);
}protected void upimagefile(fileupload fileload)
{
if (fileload.hasfile)
{
string filetype = fileload.postedfile.contenttype;
if (filetype == "image/bmp" || filetype == "image/pjpeg" || filetype == "image/gif" || filetype == "image/png")
{
string loadpath = fileload.postedfile.filename; //等待上传文件的本地路径
system.drawing.image img = system.drawing.image.fromfile(loadpath);
if (img.height > 100 || img.width > 100)
{
fileinfo info = new fileinfo(loadpath);
string fname = info.name; //获取原文件名
string filename = datetime.now.tostring("yymmddhhmmss") + fname; //在文件名中加入时间
string imgpath = server.mappath("/upfile/orimages/") + filename; //原文件路径
string thpath = server.mappath("/upfile/thimages/") + filename; //缩略图路径
fileload.saveas(imgpath); //保存原图片
makethumnail(imgpath, thpath); //生成缩略图
}
else
{
//图片尺寸太小
}
}
else
{
//文件格式不对
}}
}protected void makethumnail(string orpath, string thpath)
{
system.drawing.image img = system.drawing.image.fromfile(orpath);
int ; //设置缩略图的宽为100
int height = img.height * width / img.width; //缩略图的高按比例缩小
system.drawing.image bitmap = new system.drawing.bitmap(width, height); //创建一个空位图
system.drawing.graphics g = system.drawing.graphics.fromimage(bitmap); //创建画板
g.interpolationmode = system.drawing.drawing2d.interpolationmode.high; //设定为高质量插值
g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality; //指定高质量低速度呈现
g.clear(color.transparent);
g.drawimage(img, new rectangle(0, 0, width, height));
try
{
bitmap.save(thpath, system.drawing.imaging.imageformat.jpeg); //以jpg格式保存图片
}
catch (system.exception e)
{
throw e;
}
finally
{
img.dispose();
bitmap.dispose();
g.dispose();
}
}