[网络收集]asp.net上传图片并生成缩略图


/// <summary>

/// 上传生成缩略图

/// </summary>

/// <param name="FileUpload1">上传文件控件</param>

/// <param name="uploadFile">上传文件夹如"file/"</param>

/// <param name="ytName">保存的原图片名 不带后缀</param>

/// <param name="slName">保存的缩略图名 不带后缀</param>

/// <returns></returns>

public string MakeThumbnail(FileUpload FileUpload1, string uploadFile, string ytName, string slName, int width, int height)

{

//FileUpload1图片上传控件

if (FileUpload1.HasFile)

{

//要考虑文件大小

string filetype = FileUpload1.PostedFile.ContentType.ToLower();

if (filetype == "image/gif" || filetype == "image/png" || filetype == "image/jpeg")

{

try

{

string myTime;

string date_folder;

string gpic;

// myTime = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString("000");

string gfile = FileUpload1.PostedFile.FileName;

string pic_path = System.Web.HttpContext.Current.Server.MapPath(uploadFile); // 上传文件夹

//判断上传文件夹是否存在,不存在则创建

DirectoryInfo myFolder = new DirectoryInfo(pic_path);

if (!myFolder.Exists)

{ myFolder.Create(); }

FileInfo MyFile = new FileInfo(gfile);

gpic = ytName + MyFile.Extension;//原图名

string save_filePath = System.Web.HttpContext.Current.Server.MapPath(uploadFile + gpic);

FileUpload1.SaveAs(save_filePath); //上传原图

string gp = System.Web.HttpContext.Current.Server.MapPath(uploadFile + gpic);

string gn = System.Web.HttpContext.Current.Server.MapPath(uploadFile+slName + MyFile.Extension);//缩略图名

Stream sm = new FileStream(gp, FileMode.Open);

System.Drawing.Image img = System.Drawing.Image.FromStream(sm);

int towidth = width;//缩略图宽度

int toheight = height;//缩略图高度

int ow = img.Width;

int oh = img.Height;

if (ow > oh)

{

toheight = img.Height * towidth / img.Width;

}

else

{

towidth = img.Width * toheight / img.Height;

}

img = img.GetThumbnailImage(towidth, toheight, null, IntPtr.Zero);

img.Save(gn, System.Drawing.Imaging.ImageFormat.Jpeg);//上传缩略图

img.Dispose();

sm.Close();

sm.Dispose();

return "上传成功";

}

catch

{

return "错误!";

}

}

else

{

return "类型不符";

}

}

else

{

return "请选择文件!";

}

}

------------------test---------------------------

protected void Button1_Click(object sender, EventArgs e)

{

MakeThumbnail(FileUpload1, "file/", "wjl", "wjls", 118, 118);

FileInfo MyFile = new FileInfo(FileUpload1.PostedFile.FileName);

//删除原图

FileInfo delPic = new FileInfo(Server.MapPath("file/wjl"+MyFile.Extension));

if (delPic.Exists)

{ delPic.Delete(); }

Image1.ImageUrl = "file/wjls"+MyFile.Extension;

}

摘自 http://hi.baidu.com/wenjunlin/blog/item/ef12c1d6bc4b6f2307088bbf.html

优质内容筛选与推荐>>
1、攻防世界 web进阶区 lottery
2、Hibernate(五)
3、Kubernetes 集群组件
4、房屋风水学
5、filter,orderBy等过滤器


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号