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#程序设计有所帮助。

(0)

相关推荐

  • C# 最齐全的上传图片方法

    方法里包括了图片大小限制.图片尺寸.文件内容等等的判断... 该案例是mvc下的demo,支持单张图片上传. public ActionResult Upload() { string imgurl = ""; foreach (string key in Request.Files) { //这里只测试上传第一张图片file[0] HttpPostedFileBase file0 = Request.Files[key]; //转换成byte,读取图片MIME类型 Stream st

  • c#多图片上传并生成缩略图的实例代码

    前台代码: 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&q

  • c#生成缩略图不失真的方法实例分享

    复制代码 代码如下: /// <summary>/// 获得缩微图/// </summary>/// <returns></returns>  public bool GetThumbImg(){try{string imgpath; //原始路径     if(imgsourceurl.IndexOf("\",0)<0) //使用的是相对路径     {imgpath = HttpContext.Current.Server.Ma

  • C# 手动/自动保存图片的实例代码

    view plaincopy to clipboardprint? 复制代码 代码如下: //手动保存图片           private void saveBtn_Click(object sender, System.EventArgs e)           {               bool isSave = true;               SaveFileDialog saveImageDialog = new SaveFileDialog();          

  • c#生成缩略图的实现方法

    复制代码 代码如下: private void SaveThumbnail(Bitmap originBitmap, int width, int height, string directory, string filename, string extension){    var physicalPath = directory + filename + extension; using (var newImage = new Bitmap(width, height))    {     

  • C#给图片加水印的简单实现方法

    本文实例讲述了C#给图片加水印的简单实现方法.分享给大家供大家参考.具体分析如下: 这里实现本网站图片保护功能类: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing;//image的命名空间 namespace 实现本网站图片保护功能 { public class yanzhengma:IHttpHandler { public boo

  • c#读取图像保存到数据库中(数据库保存图片)

    复制代码 代码如下: 注:MyTools.g_PhotoField为数据库表中的图象字段名称//将图片保存到数据库中    if(this.picPhoto.Image==null)    {     m_DataRow[MyTools.g_PhotoField]=DBNull.Value;    }    else    {     try      {      MemoryStream ms = new MemoryStream ();      picPhoto.Image.Save (

  • C#中按指定质量保存图片的实例代码

    在程序中直接生产jpg图片,质量不如原图,是因为微软的Image.Save方法保存到图片压缩质量为75,所以保存的图片质量偏低了,要使生成的图片质量有所提高就需要自己设定EncoderParameters类的质量参数和ImageCodecInfo类的图片保存格式. System.Drawing.Imaging.Encoder类来制定需要呈现的方式和各种参数,例如图片质量参数,扫描方法参数,色度表参数,压缩参数,颜色深度等等.到此,大家应该明白修改图片质量的步骤和方法了.主要就是对System.D

  • c#批量上传图片到服务器示例分享

    客户端代码: 复制代码 代码如下: /// <summary>/// 批量上传图片/// </summary>/// <param name="srcurl">服务器路径</param>/// <param name="imagesPath">图片文件夹路径</param>/// <param name="files">图片名称</param>publ

  • C#保存图片到数据库并读取显示图片的方法

    复制代码 代码如下: private void button2_Click_1(object sender, System.EventArgs e) { string pathName; if (this.openFileDialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK) { pathName = this.openFileDialog1.FileName; System.Drawing.Image img = System.D

  • C#给图片添加水印完整实例

    本文实例讲述了C#给图片添加水印的方法.分享给大家供大家参考,具体如下: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Syste

随机推荐