隐藏

C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte

发布:2022/6/29 10:42:30作者:管理员 来源:本站 浏览次数:1303

using Maticsoft.Model.DTO;
using OnlineAPI.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using Maticsoft.Common;
using System.IO;
using System.Net.Http.Headers;
using System.Text;

namespace OnlineAPI.Controllers
{
    /// <summary>
    /// 验证码服务
    /// </summary>
    [RoutePrefix("code")]
    public class CodeController : BaseController
    {

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="guid"></param>
        [HttpGet,Route("CreateCheckCodeImage")]
        public void CreateCheckCodeImage(string guid)
        {
            if (string.IsNullOrEmpty(guid)) {
                return;
            }
            string checkCode = CodeHelper.MakeValidateCode();
            _Redis.Set(guid, checkCode, 1);
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 14.5)), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (int i = 0; i < 3; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Green, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);
                //画图片的前景噪音点
                for (int i = 0; i < 30; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ContentType = "image/Gif";
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// WebApi返回图片
        /// </summary>
        [HttpGet, Route("GetQrCode")]
        public HttpResponseMessage GetQrCode0(string guid)
        {
            if (string.IsNullOrEmpty(guid))
            {
                return null;
            }
            string checkCode = CodeHelper.MakeValidateCode();
            _Redis.Set(guid, checkCode, 1);
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return null;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 14.5)), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (int i = 0; i < 3; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Green, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);
                //画图片的前景噪音点
                for (int i = 0; i < 30; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ContentType = "image/Gif";
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                var resp = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    //Content = new ByteArrayContent(imgByte)
                    //或者
                    Content = new StreamContent(ms)
                };
                resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                return resp;
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }

        }
        /// <summary>
        /// WebApi返回图片
        /// </summary>
        public HttpResponseMessage GetQrCode()
        {
            var imgPath = @"D:\ITdosCom\Images\itdos.jpg";
            //从图片中读取byte
            var imgByte = File.ReadAllBytes(imgPath);
            //从图片中读取流
            var imgStream = new MemoryStream(File.ReadAllBytes(imgPath));
            var resp = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(imgByte)
                //或者
                //Content = new StreamContent(stream)
            };
            resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
            return resp;
        }
        /// <summary>
        /// WebApi返回json数据
        /// </summary>
        public HttpResponseMessage GetQrCode1()
        {
            var jsonStr = "{\"IsSuccess\":true,\"Data\":\"www.itdos.com\"}";
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(jsonStr, Encoding.UTF8, "text/json")
            };
            return result;
        }
        /// <summary>
        /// WebApi返回字符串
        /// </summary>
        public HttpResponseMessage GetQrCode2()
        {
            var str = "IT大师www.itdos.com";
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(str, Encoding.UTF8, "text/plain")
            };
            return result;
        }

    }
}