欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现的上传图片、保存图片、加水印、生成缩略图功能示例

程序员文章站 2023-12-10 09:29:28
本文实例讲述了c#实现的上传图片、保存图片、加水印、生成缩略图功能。分享给大家供大家参考,具体如下: 伴随移动设备地普及,处理图片、视频等需求也变得越来越基础,这里介绍的...

本文实例讲述了c#实现的上传图片、保存图片、加水印、生成缩略图功能。分享给大家供大家参考,具体如下:

伴随移动设备地普及,处理图片、视频等需求也变得越来越基础,这里介绍的是图片的存储。

上传图片必须使用form表单提交的方式,我只知道这一种方法,如果大家知道其他方法的话请留言。

保存图片、加水印和生成缩略图这三种功能最好各自放在单独的方法中,尽量降低耦合度,提高代码复用程度,除此之外我们平常写代码是也要尽量做到方法功能的唯一性。

前台代码:

<form method="post" enctype="multipart/form-data" action="uploadimg.ashx">
  <table>
    <tr>
      <td>func:</td>
      <td><input type="text" name="func"/></td>
    </tr>
    <tr>
      <td>用户id:</td>
      <td><input type="text" name="userid"/></td>
    </tr>
    <tr>
      <td>头像:</td>
      <td><input type="file" name="icon"/></td>
    </tr>
    <tr>
      <td>水印:</td>
      <td><input type="text" name="watermark"/></td>
    </tr>
  </table>
  <input type="submit" value="提交"/>
</form>

后台代码:

private string uploadimage(httpcontext context)
{
  try
  {
    system.io.stream stream = context.request.files["icon"].inputstream;
    //返回的图片路径可以存储在数据库中
    string imageurl = saveimage(stream, "icon", "蝈蝈");
    string thumbnailimageurl = savethumbnailimage(stream, "icon");
    string thumbnailimageurlwithwatermark = savethumbnailimage(configurationmanager.appsettings["attachmentsdirectory"] + imageurl, "icon");
    return "上传成功!";
  }
  catch (exception ex)
  {
    return "上传失败!";
  }
}
private string saveimage(stream stream, string foldername, string watermark)
{
  try
  {
    string filename = guid.newguid() + ".jpg";
    string path = configurationmanager.appsettings["attachmentsdirectory"];
    path = path.combine(path, foldername + "\\" + datetime.now.year + "\\" + datetime.now.month + "\\" + datetime.now.day + "\\");
    string imageurl = "/" + foldername + "/" + datetime.now.year + "/" + datetime.now.month + "/" + datetime.now.day + "/";
    if (!string.isnullorempty(watermark))
    {
      image imgsource = image.fromstream(stream);
      addwatermarkandsave(path, filename, watermark, imgsource, imgsource.height - 300, 10, color.red,
        new font("宋体", 40));
    }
    else
    {
      byte[] buffer = new byte[stream.length];
      stream.read(buffer, 0, buffer.length);
      if (!directory.exists(path))
      {
        directory.createdirectory(path);
      }
      system.io.filestream fs = new system.io.filestream(path + filename, system.io.filemode.openorcreate,
        system.io.fileaccess.write);
      fs.write(buffer, 0, buffer.length);
      fs.flush();
      fs.close();
    }
    return imageurl + filename;
  }
  catch (exception ex)
  {
    return "";
  }
}
private string savethumbnailimage(stream stream, string foldername)
{
  try
  {
    string filename = guid.newguid() + ".jpg";
    string path = configurationmanager.appsettings["attachmentsdirectory"];
    path = path.combine(path, foldername + "\\" + datetime.now.year + "\\" + datetime.now.month + "\\" + datetime.now.day + "\\");
    string imageurl = "/" + foldername + "/" + datetime.now.year + "/" + datetime.now.month + "/" + datetime.now.day + "/";
    system.drawing.image.getthumbnailimageabort mycallback = new system.drawing.image.getthumbnailimageabort(getfalse);
    //数据源来自stream
    image image = system.drawing.bitmap.fromstream(stream);
    system.drawing.image thumbnailimage = image.getthumbnailimage(64, 64, mycallback, intptr.zero);
    thumbnailimage.save(path + filename);
    thumbnailimage.dispose();
    return imageurl + filename;
  }
  catch (exception ex)
  {
    return "";
  }
}
private string savethumbnailimage(string originalfilename, string foldername)
{
  try
  {
    string filename = guid.newguid() + ".jpg";
    string path = configurationmanager.appsettings["attachmentsdirectory"];
    path = path.combine(path, foldername + "\\" + datetime.now.year + "\\" + datetime.now.month + "\\" + datetime.now.day + "\\");
    string imageurl = "/" + foldername + "/" + datetime.now.year + "/" + datetime.now.month + "/" + datetime.now.day + "/";
    system.drawing.image.getthumbnailimageabort mycallback = new system.drawing.image.getthumbnailimageabort(getfalse);
    //数据源来自file
    image image = system.drawing.bitmap.fromfile(originalfilename);
    system.drawing.image thumbnailimage = image.getthumbnailimage(64, 64, mycallback, intptr.zero);
    thumbnailimage.save(path + filename);
    thumbnailimage.dispose();
    return imageurl + filename;
  }
  catch (exception ex)
  {
    return "";
  }
}
private bool getfalse()
{
  return false;
}
/// <summary>
/// 图片加文字水印
/// </summary>
/// <param name="filename"> </param>
/// <param name="text">水印文字,如果是多行用分号隔开</param>
/// <param name="img">图片</param>
/// <param name="paddingtop">上边距</param>
/// <param name="paddingleft">左边距</param>
/// <param name="textcolor">文字颜色</param>
/// <param name="textfont">字体</param>
/// <param name="path">保存地址</param>
/// <returns></returns>
private bool addwatermarkandsave(string path, string filename, string text, image img,
      int paddingtop, int paddingleft, color textcolor, font textfont)
{
  text = text + ";" + "当前时间:" + datetime.now.tostring("yyyy-mm-dd hh:mm");
  if (!directory.exists(path))
  {
    directory.createdirectory(path);
  }
  textfont = new font("宋体", 19);
  bitmap bm = new bitmap(img);
  system.drawing.graphics g = system.drawing.graphics.fromimage(bm);
  system.drawing.brush b = new solidbrush(textcolor);
  string[] str = text.split(';');
  for (int i = 0; i < str.length; i++)
    g.drawstring(str[i], textfont, b, paddingleft, paddingtop + 33 * i);
  g.dispose();
  bm.save(path + filename, imageformat.jpeg);
  bm.dispose();
  return true;
}

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#图片操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。