zoukankan      html  css  js  c++  java
  • 动态在网络图片上写字

    1、由于网络安全性,所以不能再网络图片上写字,首先进行图片下载,然后在本地进行写字

    具体调用代码如下:

    Dictionary<string, string> dic_User = new Dictionary<string, string>();
                    dic_User.Add("input", "" + ds.Tables[0].Rows[0]["surname"] + ds.Tables[0].Rows[0]["userName"] + "");//当前接收发证人的姓名
                    dic_User.Add("x", "600");
                    dic_User.Add("y", "700");
                    dic_User.Add("middle", "true");//是否居中显示  true 居中 false 不居中
    
                    Dictionary<string, string> dic_CourseName = new Dictionary<string, string>();
                    dic_CourseName.Add("input", "" + ds.Tables[0].Rows[0]["courseName"] + "");//课程名称
                    dic_CourseName.Add("x", "600");
                    dic_CourseName.Add("y", "900");
                    dic_CourseName.Add("middle", "true");//是否居中显示  true 居中 false 不居中
    
                    Dictionary<string, string> dic_Time = new Dictionary<string, string>();
                    dic_Time.Add("input", "" + Convert.ToDateTime(ds.Tables[0].Rows[0]["StartTime"]).ToString("yyyy.MM.dd") + "-" + Convert.ToDateTime(ds.Tables[0].Rows[0]["EndTime"]).ToString("yyyy.MM.dd") + "");//证书有效期
                    dic_Time.Add("x", "600");
                    dic_Time.Add("y", "1200");
                    dic_Time.Add("middle", "true");//是否居中显示  true 居中 false 不居中
    
                    Dictionary<string, string> dic_teacher = new Dictionary<string, string>();  //学员讲师
                    dic_teacher.Add("input", "" + ds.Tables[0].Rows[0]["teacher"] + "");
                    dic_teacher.Add("x", "400");
                    dic_teacher.Add("y", "1500");
                    dic_teacher.Add("middle", "flase");//是否居中显示  true 居中 false 不居中
    
    
                    List<Dictionary<string, string>> listdict = new List<Dictionary<string, string>>();
                    listdict.Add(dic_User);
                    listdict.Add(dic_CourseName);
                    listdict.Add(dic_Time);
                    listdict.Add(dic_teacher);
    
                    BuildImage.CreateImgage(listdict, Color.Black, ConfigurationManager.AppSettings["examfile"].ToString() + ds.Tables[0].Rows[0]["Url"], tid);
    
                    ImagePrint.ImageUrl = "tempPic/" + tid + ".jpg";

    具体实现代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Drawing.Drawing2D;
    using System.Net;
    
    namespace ELearning.ELearning.Common
    {
        /// <summary>
        /// 图片提供程序
        /// create by gaoxing 
        /// 2013-06-09
        /// </summary>
        public static class ImageProvider
        {
            private static BuildImage buildImage = null;
    
            /// <summary>
            /// 生成图片
            /// create by gaoxing 
            /// 2013-06-09
            /// </summary>
            public static BuildImage Provider
            {
                get
                {
                    if (buildImage == null)
                    {
                        buildImage = new BuildImage();
                    }
                    return buildImage;
                }
            }
        }
    
        public class BuildImage
        {
            private static Matrix m = new Matrix();
    
            // 定义字体
            private static Font[] fonts = {
                                            new Font(new FontFamily("Times New Roman"), 18, FontStyle.Bold),
                                            new Font(new FontFamily("Georgia"), 18 , FontStyle.Bold),
                                            new Font(new FontFamily("Helvetica"), 18, FontStyle.Bold),
                                            new Font(new FontFamily("Arial"), 18 , FontStyle.Bold)
                                         };
    
            /// <summary>
            /// 生成图片
            /// create by gaoxing 2013-06-09
            /// </summary>
            /// <param name="str">传入字符串</param>
            /// <param name="bgImg">当前图片对象</param>
            /// <param name="x">X坐标</param>
            /// <param name="y">Y坐标</param>
            /// <param name="color">当前字体颜色</param>
            /// <param name="middle">是否居中显示  true 居中显示  false 不居中显示</param>
            /// <returns></returns>
            private ImageInfo GenerateImage(string str, System.Drawing.Image bgImg, float x, float y, Color color, object middle)
            {
    
    
    
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.ImageFormat = ImageFormat.Jpeg;
                imageInfo.ContentType = "image/pjpeg";
    
                Bitmap bitmap = new Bitmap(bgImg, bgImg.Width, bgImg.Height);
                Graphics g = Graphics.FromImage(bitmap);
                //是否居中显示
                if (middle != null)
                {
                    if (middle.ToString() == "true")
                    {
                        //设置X坐标
                        x = SetX(str, x, bitmap, g);
                    }
                }
    
                // 定义前景色 字体颜色
                SolidBrush drawBrush = new SolidBrush(color);
    
                // 写字
                g.DrawString(str, fonts[3], drawBrush, new PointF(x, y));
    
    
                GetStringLength(str, g);
    
    
                g.ResetTransform();
    
                drawBrush.Dispose();
                g.Dispose();
                g.Dispose();
    
                imageInfo.Image = bitmap;
    
                return imageInfo;
            }
            /// <summary>
            /// 设置X坐标(居中显示)
            /// create by gaoxing 
            /// </summary>
            /// <param name="str">当前要显示的字符串</param>
            /// <param name="x">X坐标</param>
            /// <param name="bitmap">当前的图片对象</param>
            /// <param name="g">当前的图形对象</param>
            /// <returns>更新后的X</returns>
            private static float SetX(string str, float x, Bitmap bitmap, Graphics g)
            {
                /////////////////////计算字符串的长度/////////////////////////
                Graphics tmpG = g;
                SizeF size = tmpG.MeasureString(str, fonts[3]);
                float length = size.Width;
                //////////////////////////////////////////////
                //计算当前字符串的长度
                //计算当前字符串的起始像素
                float piclength = bitmap.Width;
                x = (piclength / 2) - (length / 2)-25;
                return x;
            }
            /// <summary>
            /// 获取当前字符串的像素长度
            /// create by gaoxing 
            /// </summary>
            /// <param name="str">输入字符串</param>
            /// <param name="g"></param>
            private static float GetStringLength(string str, Graphics g)
            {
                /////////////////////计算字符串的长度/////////////////////////
                Graphics tmpG = g;
                SizeF size = tmpG.MeasureString(str, fonts[3]);
                float StringWidth = size.Width;
                return StringWidth;
                //////////////////////////////////////////////
            }
            /// <summary>
            /// 下载文件
            /// create by 高兴
            /// 2013-06-09
            /// </summary>
            /// <param name="uriString">网络路径地址</param>
            /// <param name="id">当前Id</param>
            /// <returns></returns>
            private static string DownLoadFile(string uriString, string id)
            {
                Uri address = new Uri(uriString);
                string fileName = HttpContext.Current.Server.MapPath("TempPic") + @"" + id + "Model.jpg";
                using (WebClient wc = new WebClient())
                {
                    try
                    {
                        wc.DownloadFile(address, fileName);
                    }
                    catch { }
                    return fileName;
                }
            }
            /// <summary>
            /// 生成图片,主方法调用
            /// 传入数据集合
            /// 每个字典为一组输入数据
            /// key=input:要打印的字符
            /// key=x X坐标
            /// key=y X坐标
            /// Create by gaoxing
            /// 2013-06-09
            /// </summary>
            /// <param name="listdict">集合数据</param>
            /// <param name="color">当前字体颜色</param>
            /// <param name="ImgUrl">图片网络路径</param>
            /// <param name="imgId">图片Id</param>
            /// <returns></returns>
            public static void CreateImgage(List<Dictionary<string, string>> listdict, Color color, string ImgUrl, string imgId)
            {
                ////更改Http头
                //HttpContext.Current.Response.ClearContent();
                //HttpContext.Current.Response.ContentType = "image/pjpeg";
    
                //HttpContext.Current.Response.BinaryWrite(BuildImage.GetImage(listdict, color, BuildImage.DownLoadFile(ImgUrl, imgId)).ToArray());
                //HttpContext.Current.Response.End();
    
    
    
                string fileName = HttpContext.Current.Server.MapPath("TempPic") + "/" + imgId + ".jpg";
    
                using (MemoryStream ms = new MemoryStream(BuildImage.GetImage(listdict, color, BuildImage.DownLoadFile(ImgUrl, imgId)).ToArray()))
                {
                    Image image = new Bitmap(ms, true);
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    image.Save(fileName);
                }
    
    
            }
            /// <summary>
            /// 传入数据集合
            /// 每个字典为一组输入数据
            /// key=input:要打印的字符
            /// key=x X坐标
            /// key=y X坐标
            /// Create by gaoxing
            /// 2013-06-09
            /// </summary>
            /// <param name="listdict">集合数据</param>
            /// <param name="color">当前字体颜色</param>
            /// <param name="imgPath">图片路径</param>
            /// <returns></returns>
            private static MemoryStream GetImage(List<Dictionary<string, string>> listdict, Color color, string imgPath)
            {
                BuildImage buildImage = ImageProvider.Provider;
                ImageInfo imageInfo = new ImageInfo();
                using (MemoryStream ms = new MemoryStream())
                {
                    int i = 0;
                    foreach (Dictionary<string, string> dic in listdict)
                    {
                        if (i < 1)
                        {
                            imageInfo = buildImage.GenerateImage(dic["input"].ToString(), System.Drawing.Image.FromFile(imgPath), float.Parse(dic["x"].ToString()), float.Parse(dic["y"].ToString()), color, dic["middle"].ToString());
                        }
                        else
                        {
                            imageInfo = buildImage.GenerateImage(dic["input"].ToString(), imageInfo.Image, float.Parse(dic["x"].ToString()), float.Parse(dic["y"].ToString()), color, dic["middle"].ToString());
                        }
                        i++;
                    }
    
                    long with = System.Drawing.Image.FromFile(imgPath).Width;
    
                    imageInfo.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return ms;
                }
            }
        }
    
        /// <summary>
        /// 图片信息
        /// create by gaoxing 
        /// 2013-06-09
        /// </summary>
        public class ImageInfo
        {
            private Bitmap image;
            private string contentType = "image/pjpeg";
            private ImageFormat imageFormat = ImageFormat.Jpeg;
    
            /// <summary>
            /// 生成的图片
            /// </summary>
            public Bitmap Image
            {
                get { return image; }
                set { image = value; }
            }
    
            /// <summary>
            /// 图片类型,如 image/pjpeg
            /// </summary>
            public string ContentType
            {
                get { return contentType; }
                set { contentType = value; }
            }
    
            /// <summary>
            /// 图片格式
            /// </summary>
            public ImageFormat ImageFormat
            {
                get { return imageFormat; }
                set { imageFormat = value; }
            }
        }
    }
  • 相关阅读:
    PAT 1036 Boys vs Girls (25分) 比大小而已
    idea创建maven项目慢的原因以及解决方案
    git diff 理解
    git status 命令详解
    java注解
    单例模式
    io分类
    数据库设计的范式
    mysql约束
    mysql去重复关键字distinct的用法
  • 原文地址:https://www.cnblogs.com/happygx/p/3265669.html
Copyright © 2011-2022 走看看