winform及ajax调用webapi接受base64图片 然后加水印

winform及ajax调用webapi

winform`

/// <summary>
               /// 调用api返回json
               /// </summary>
               /// <param name="url">api地址</param>
               /// <param name="jsonstr">接收参数</param>
               /// <param name="type">类型</param>
               /// <returns></returns>
        public static string HttpApi(string url, string jsonstr, string type)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
            request.Accept = "text/html,application/xhtml+xml,*/*";
            request.ContentType = "application/json";
            request.Method = type.ToUpper().ToString();//get或者post
            byte[] buffer = encoding.GetBytes(jsonstr);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
    }`

ajax

var postData = {
                        key:"1",
        }
        $.post("http://localhost:62300/api/UploadImg/",postData, function (resp) {
            alert(resp);
            alert(resp.Success);
        });

webapi

using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace ORCodeWeb.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    /// 
    //[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]

    public class UploadImgController : ApiController
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="postJson"></param>
        /// <returns></returns>
        public HttpResponseMessage Post([FromBody]JObject postJson)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            ResultMsg msg = new ResultMsg();
            string json = postJson.ToString();
            JavaScriptSerializer js = new JavaScriptSerializer();
            var list = js.Deserialize<SelectList>(json);
            string id = list.id;
            string img = list.img;
            string key = list.key;
            string fliepathold = "";
            string fliepathnew = "";
            string savePath = "";
            string Orcode = new DAL.DALORCodes().GetORCodesList().Id;
            string oldName = string.Format("{0}.jpg", Orcode);
            string newName = string.Format("{0}_New.jpg", Orcode);
            string floderName = string.Format("/Uploads/{0:yyyy}/{0:MMdd}", DateTime.Now);
            CreateFolder(System.Web.Hosting.HostingEnvironment.MapPath(floderName));
            string oldPath = string.Format("{0}/{1}", floderName, oldName);
            string newPath = string.Format("{0}/{1}", floderName, newName);
            savePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            fliepathold = savePath + oldPath;
            fliepathnew = savePath + newPath;
            bool flag = Base64StringToImg(img, fliepathold);
            if (key == "1" && flag == true)
            {
                AddTextToImage(Orcode, fliepathold, fliepathnew);
                msg = new DAL.DALORCodes().Insert(new ORCodes { ORCodeNo = Orcode, OrgORCode = oldPath, NewORCode = newPath ,Path=floderName});
                if (msg.Success == true)
                {
                    new DAL.DALORCodes().DeleteOrlist(Orcode);
                }

            }
            msg.Success = flag;
            string str = js.Serialize(msg);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        /// <summary>
        /// 创建文件目录
        /// </summary>
        /// <param name="path">path</param>
        private void CreateFolder(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="fliepathnew"></param>
        /// <returns></returns>
        public string ImgToBase64String(string fliepathnew)
        {
            string UserPhoto = "";
            Bitmap bmp1 = new Bitmap(Path.Combine(fliepathnew));
            using (MemoryStream ms1 = new MemoryStream())
            {
                bmp1.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr1 = new byte[ms1.Length];
                ms1.Position = 0;
                ms1.Read(arr1, 0, (int)ms1.Length);
                ms1.Close();
                UserPhoto = Convert.ToBase64String(arr1);
            }
            return UserPhoto;
        }
        /// <summary>
        /// base64转图片
        /// </summary>
        /// <param name="img"></param>
        /// <param name="fliepathold"></param>
        /// <returns></returns>
        public bool Base64StringToImg(string img, string fliepathold)
        {
            byte[] arr2 = Convert.FromBase64String(img);
            using (MemoryStream ms2 = new MemoryStream(arr2))
            {
                Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
                bmp2.Save(fliepathold, System.Drawing.Imaging.ImageFormat.Jpeg);
                return true;
            }
        }

        /// <summary>
        /// 定义
        /// </summary>
        public partial class SelectList
        {
            /// <summary>
            /// 
            /// </summary>
            public string id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string img { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string key { get; set; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        /// <param name="filePath"></param>
        /// <param name="savePath"></param>
        private void AddTextToImage(string text, string filePath, string savePath)
        {


            if (string.IsNullOrEmpty(text))
                return;

            Image image = Image.FromFile(filePath);

            Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
            Graphics g = Graphics.FromImage(bitmap);

            float fontSize = 22f;
            float textWidth = (fontSize / 72) * 96;

            Font font = new Font("Calibri", fontSize, FontStyle.Bold);

            //字体矩形位置 :
            float rectX = image.Width - 60;
            float rectY = image.Height - image.Height / 2 - 100;

            float rectWidth = 60;
            float rectHeight = 220;
            //画矩形
            RectangleF textArea = new RectangleF(rectX + 8, rectY + 2, rectWidth - 30, rectHeight);

            Brush bai = new SolidBrush(Color.White);
            Brush hui = new SolidBrush(Color.FromArgb(217, 217, 217));
            //g.FillRectangle(hui , rectX, rectY, rectWidth, rectHeight);
            FillRoundRectangle(g, hui, new Rectangle(Convert.ToInt32(rectX), Convert.ToInt32(rectY), Convert.ToInt32(rectWidth), Convert.ToInt32(rectHeight)), 10);
            g.DrawString(text, font, bai, textArea, new StringFormat(StringFormatFlags.DisplayFormatControl));
            bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            g.Dispose();
            bitmap.Dispose();
            image.Dispose();

        }
        /// <summary>
        /// 绘线
        /// </summary>
        /// <param name="g"></param>
        /// <param name="pen"></param>
        /// <param name="rect"></param>
        /// <param name="cornerRadius"></param>
        public static void DrawRoundRectangle(Graphics g, Pen pen, Rectangle rect, int cornerRadius)
        {
            using (GraphicsPath path = CreateRoundedRectanglePath(rect, cornerRadius))
            {
                g.DrawPath(pen, path);
            }
        }
        /// <summary>
        /// 绘面
        /// </summary>
        /// <param name="g"></param>
        /// <param name="brush"></param>
        /// <param name="rect"></param>
        /// <param name="cornerRadius"></param>
        public static void FillRoundRectangle(Graphics g, Brush brush, Rectangle rect, int cornerRadius)
        {
            using (GraphicsPath path = CreateRoundedRectanglePath(rect, cornerRadius))
            {
                g.FillPath(brush, path);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rect"></param>
        /// <param name="cornerRadius"></param>
        /// <returns></returns>
        internal static GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int cornerRadius)
        {
            GraphicsPath roundedRect = new GraphicsPath();

            roundedRect.AddArc(rect.X, rect.Y, cornerRadius * 2, cornerRadius * 2, 180, 90);
            roundedRect.AddLine(rect.X + cornerRadius, rect.Y, rect.Right - cornerRadius * 2, rect.Y);

            //roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y, cornerRadius * 2, cornerRadius * 2, 270, 90);
            //roundedRect.AddLine(rect.Right, rect.Y + cornerRadius * 2, rect.Right, rect.Y + rect.Height - cornerRadius * 2);

            //roundedRect.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y + rect.Height - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);
            roundedRect.AddLine(rect.Right - cornerRadius * 2, rect.Bottom, rect.X + cornerRadius * 2, rect.Bottom);

            roundedRect.AddArc(rect.X, rect.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);
            roundedRect.AddLine(rect.X, rect.Bottom - cornerRadius * 2, rect.X, rect.Y + cornerRadius * 2);
            roundedRect.CloseFigure();
            return roundedRect;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值