服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#实现的上传图片、保存图片、加水印、生成缩略图功能示例

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

2022-03-10 14:08changuncle C#

这篇文章主要介绍了C#实现的上传图片、保存图片、加水印、生成缩略图功能,结合实例形式较为详细的分析了C#图片上传、保存、水印、缩略图等相关操作技巧,需要的朋友可以参考下

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

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

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

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

前台代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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>

后台代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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#程序设计有所帮助。

原文链接:https://blog.csdn.net/xiaouncle/article/details/54883327

延伸 · 阅读

精彩推荐
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21