bootstrap-wysiwyg 结合 base64 解码 .net bbs 图片操作类

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Net;

using System.IO;

using KT_Product_Show_V3.Models;

using KT_Product_Show_V3.Controllers;

using System.Text.RegularExpressions;

using System.Drawing.Imaging;



namespace KT_Product_Show_V3

{

  public partial class ImageTool

  {

    public static string BuildImg(string webUrl, int Size, string directory)

    {

      Bitmap bmp;

      System.Drawing.Image img;

      string filename = "";

      if (!Directory.Exists(directory))

      {

        return "";

      }

      WebRequest WebReq = WebRequest.Create(webUrl);

      WebReq.Method = "GET";

      img = System.Drawing.Image.FromStream(WebReq.GetResponse().GetResponseStream());

      bmp = new Bitmap(Size, Size);

      System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);

      gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

      gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

      gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

      System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, Size, Size);

      gr.DrawImage(img, rectDestination, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);

      filename = DateTime.Now.ToFileTime().ToString() + "_" + Size + ".jpeg";

      bmp.Save(directory + filename);

      Qiniu_API.PutFile(directory + filename, filename);

      bmp.Dispose();

      img.Dispose();

      return filename;

    }



    public static string Base64StringToImage(string strsuffix, string strbase64)

    {

      string path = "C:\\DescripttionImg\\";

      string FileName_withOutstrsuffix = DateTime.Now.ToString("yyMMddhhmmss") + Guid.NewGuid().ToString("N");

      string FileName = string.Format(@"{0}.{1}", FileName_withOutstrsuffix, strsuffix);

      if (!Directory.Exists(path))

      {

        Directory.CreateDirectory(path);

      }

      try

      {

        byte[] arr = Convert.FromBase64String(strbase64);

        MemoryStream ms = new MemoryStream(arr);

        Bitmap bmp = new Bitmap(ms);

        bmp.Save(path + FileName);

        ms.Close();



        Qiniu_API.PutFile(path + FileName, FileName);



      }

      catch (Exception ex)

      {



      }

      finally

      {



      }

      return string.Format("http://{0}/{1}", Qiniu_API.Domain, FileName);

    }



    public static string ImgToBase64String(string Imagefilename)

    {

      try

      {

        Bitmap bmp = new Bitmap(Imagefilename);



        MemoryStream ms = new MemoryStream();

        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        byte[] arr = new byte[ms.Length];

        ms.Position = 0;

        ms.Read(arr, 0, (int)ms.Length);

        ms.Close();

        return Convert.ToBase64String(arr);

      }

      catch (Exception ex)

      {

        return null;

      }

    }



    public static string DescripttionDecode(string str)

    {

      string pattern = @"data:image/[a-z]+;base64,([a-z0-9-A-z]|[\+]|[/\\]|[=])*";

      string pattern_suffix = @"data:image/[a-z]+;base64,";

      RegexOptions regexOptions = RegexOptions.None;

      Regex regex = new Regex(pattern, regexOptions);

      Regex regex_suffix = new Regex(pattern_suffix, regexOptions);

      foreach (Match match in regex.Matches(str))

      {

        if (match.Success)

        {

          string path = "";

          string Temp = regex_suffix.Match(match.Value).Value;

          string suffix = Temp.Replace("data:image/", "").Replace(";base64,", "");

          string base64 = match.Value.Replace(Temp, "");

          path = Base64StringToImage(suffix, base64);

          str = str.Replace(match.Value, path);



        }

      }



      return str;

    }



    public static string DescripttionDecodeCutMaxWidth(string str, int MaxWidth)

    {

      string pattern = @"data:image/[a-z]+;base64,([a-z0-9-A-z]|[\+]|[/\\]|[=])*";

      string pattern_suffix = @"data:image/[a-z]+;base64,";

      RegexOptions regexOptions = RegexOptions.None;

      Regex regex = new Regex(pattern, regexOptions);

      Regex regex_suffix = new Regex(pattern_suffix, regexOptions);

      foreach (Match match in regex.Matches(str))

      {

        if (match.Success)

        {

          string path = "";

          string Temp = regex_suffix.Match(match.Value).Value;

          string suffix = Temp.Replace("data:image/", "").Replace(";base64,", "");

          string base64 = match.Value.Replace(Temp, "");

          path = Base64StringToImageCutMaxWidth(suffix, base64,MaxWidth);

          str = str.Replace(match.Value, path);



        }

      }



      return str;

    }

    public static string Base64StringToImageCutMaxWidth(string strsuffix, string strbase64, int MaxWidth)

    {

      string path = "C:\\DescripttionImg\\";

      string FileName_withOutstrsuffix = DateTime.Now.ToString("yyMMddhhmmss") + Guid.NewGuid().ToString("N");

      string FileName = string.Format(@"{0}.{1}", FileName_withOutstrsuffix, strsuffix);

      if (!Directory.Exists(path))

      {

        Directory.CreateDirectory(path);

      }

      try

      {

        byte[] arr = Convert.FromBase64String(strbase64);

        MemoryStream ms = new MemoryStream(arr);

        Bitmap bmp = new Bitmap(ms);

        if (bmp.Width > MaxWidth)

        {

          bmp = KiResizeImage(bmp, MaxWidth, MaxWidth * bmp.Height / bmp.Width);

        }



        // bmp.Width = MaxWidth;

        // bmp.Height

        bmp.Save(path + FileName);

        ms.Close();



        Qiniu_API.PutFile(path + FileName, FileName);



      }

      catch (Exception ex)

      {



      }

      finally

      {



      }

      return string.Format("http://{0}/{1}", Qiniu_API.Domain, FileName);

    }

    public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH)

    {

      try

      {

        Bitmap b = new Bitmap(newW, newH);

        Graphics g = Graphics.FromImage(b);



        // 插值算法的质量

        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

        //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);

        g.Dispose();



        return b;

      }

      catch

      {

        return null;

      }

    }



  }

}


先上传到本地 然后到 七牛云 存储,最后 ,在 bbs 上显示 图片 直接 来源于七牛,本地也保存了一份,后续扩展到一键切换到本地读取功能。还可以使用负载均衡。

上面这个  图片操作类 还提供了 头像裁剪 之后 的 上传 大、小 图片 的方法。

[HttpPost]

    [ValidateInput(false)]

    public void AddDescripttion()

    {

      if (Request.Form["Descripttion"] == null)

      {

        Response.Write(0);

        Response.End();



      }

      string str = Request.Form["Descripttion"].ToString();

      Discuz discuz = new Discuz();

      discuz.CreateTime = DateTime.Now;

      discuz.Descripttion = ImageTool.DescripttionDecode(str);

      discuz.Floor = conn.Database.SqlQuery<int>("select isnull( max(Floor),0) from dbo.Discuz").FirstOrDefault() + 1;

      discuz.ForumId = 1;

      discuz.IsFather = true;

      discuz.Isgood = 0;

      discuz.IsPass = 1;

      discuz.UserId = 1;

      conn.Discuz.Add(discuz);

      conn.SaveChanges();

      Response.Write(1);

      Response.End();

    }

MVC  bbs发表帖子 的调用 action , [ValidateInput(false)]  结合 网站 web.config 文件 中的  <system.webServer> 下的<validation validateIntegratedModeConfiguration="false" />  一起用 ,才能解决

从客户端 中检测到有潜在危险的 Request.Form 值  报错的问题。
   

 还介绍一个好的  Regex 工具

下载之后 我找了 半天 ,原来 在 这里啊!

 

img  的 src 属性 可以 是 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA

AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO

9TXL0Y4OHwAAAABJRU5ErkJggg==" >  这种不支持图片缓存。

 

你可能感兴趣的:(bootstrap)