C#生成縮略圖代碼
2024-07-21 02:25:55
供稿:網友
if(fileupload.postedfile!=null)
{
//addto為要添加的屬性,aboutfile為文件說明
string nam = fileupload.postedfile.filename ;
//取得文件名(抱括路徑)里最后一個"."的索引
int i= nam.lastindexof(".");
//取得文件擴展名
string newext =nam.substring(i);
//這里我自動根據日期和文件大小不同為文件命名,確保文件名不重復
datetime now = datetime.now;
string newname=now.dayofyear.tostring()+fileupload.postedfile.contentlength.tostring();
//保存文件到你所要的目錄,這里是iis根目錄下的upload目錄.你可以改變.
//注意: 我這里用server.mappath()取當前文件的相對目錄.在asp.net里"/"必須用"http://"代替,把"upload//"改成"http://upload//"就成了取當前文件的絕對目錄了
fileupload.postedfile.saveas(server.mappath("upload//"+newname+newext));
//得到這個文件的相關屬性:文件名,文件類型,文件大小
//fname.text=myfile.postedfile.filename;
//fenc.text=myfile.postedfile.contenttype ;
//fsize.text=myfile.postedfile.contentlength.tostring();
//下面是生成縮略圖
system.drawing.image image,anewimage;
int width,height,newwidth,newheight;
image=system.drawing.image.fromfile(server.mappath("upload/"+newname.tostring()+newext.tostring()));
system.drawing.image.getthumbnailimageabort callb =new system.drawing.image.getthumbnailimageabort(thumbnailcallback);
width=image.width;
height=image.height;
if(firstpageshow.selectedvalue.tostring()=="1"&&fenlei.selectedvalue.tostring()=="5")
{
newwidth=203;newheight=86;
newheight=height*newwidth/width;
}
else if(isweekman.selectedvalue.tostring()=="1")
{
newwidth=171;newheight=111;
newheight=height*newwidth/width;
}
else if(firstpageshow.selectedvalue.tostring()=="1"&&fenlei.selectedvalue.tostring()=="3")
{
newwidth=171;newheight=111;
newheight=height*newwidth/width;
}
else
{
newwidth=62;newheight=80;
newheight=height*newwidth/width;
}
anewimage=image.getthumbnailimage(newwidth,newheight,callb,new system.intptr());
anewimage.save(server.mappath("upload//"+"small_"+newname+newext));
image.dispose();
//生成縮略圖 生成并保存完畢,保存名是在原圖名前加了一個small_。
pic="upload/"+newname.tostring()+newext.tostring();
smallpic="upload/small_"+newname.tostring()+newext.tostring();
}