苏飞论坛

标题: c# 生成图片 并实现合成图片,添加文字,画矩形,画园等功能 [打印本页]

作者: 自强不息    时间: 2016-2-1 14:08
标题: c# 生成图片 并实现合成图片,添加文字,画矩形,画园等功能
最近工作中需要实现一个比较固定网页的生成图片的功能,首先结合自己枯死冥想,并在网上寻找搜索线索。
最好也没有找到一个好的方案。

在这里首先要感谢飞哥给予的帮助,经过飞哥的指导完成了任务。
现在我把这些天的努力,记录下来,在论坛上发个帖子,方便以后查阅,也为了有此需要的小伙伴来参考

c# 生成图片 并实现合成图片,添加文字,画矩形,画园等功能
重点记录功能
1:添加图片到画布上,并且控制好位置,大小
2:添加文字到画布上,并且控制好位置,大小,颜色,字体类型,宽度,换行等。
3:在画布上,画圆,画矩形,大小,半径,空心的,实心的等。

下面记录的实现方案

准备工作:
1:初始画布大小。(画布初始要根据自己的需求来实例)
[C#] 纯文本查看 复制代码
 //初始画布大小
  
                int initialWidth = 880, initialHeight = 2000;
                Bitmap theBitmap = new Bitmap(initialWidth, initialHeight);
                Graphics theGraphics = Graphics.FromImage(theBitmap);
                //呈现质量
                theGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                //背景色
                theGraphics.Clear(Color.FromArgb(255, 255, 255));
                //灰色边框
                theGraphics.DrawRectangle(new Pen(Color.FromArgb(227, 227, 227), 1), 1, 1, initialWidth - 2,
                    initialHeight - 2);

2:新建画刷,定义各种所需要的画刷,定义各种所需要的字体
[C#] 纯文本查看 复制代码
  
                int autoHeight = 0; //累计高度(动态的内容高度位置)
                int sjh = 0; //时间轴的高度
                float fwigth = 0;
                int fontHeight = 30; //文字行间距
                string FontType = "微软雅黑";
                string IconType = "iconfont";
                Font theFont = new Font(FontType, 18.0f, System.Drawing.FontStyle.Bold);

                //准备工作。定义画刷颜色
                Color col = Color.FromArgb(51, 51, 51);
                Brush newBrush = new SolidBrush(col);
                Brush bush = new SolidBrush(Color.FromArgb(204, 204, 204)); //填充的颜色


3:在画布上画图片。涉及技术;根据图片路径或网络地址,转换成数据流。

[C#] 纯文本查看 复制代码
 public Bitmap Get_img(string imgurl)
        {
            Bitmap img = null;
            HttpWebRequest req;
            HttpWebResponse res = null;
            try
            {
                System.Uri httpUrl = new System.Uri(imgurl);
                req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                req.Timeout = 180000; //设置超时值10秒
                req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
                req.Accept = "text/html, application/xhtml+xml, */*";
                req.Method = "GET";
                res = (HttpWebResponse)(req.GetResponse());
                img = new Bitmap(res.GetResponseStream());//获取图片流                 
               // img.Save(@"E:/" + DateTime.Now.ToFileTime().ToString() + ".png");//随机名
            }
            catch (Exception  ) { }
            return img;
        }

[C#] 纯文本查看 复制代码

Bitmap bmp = Get_img("");//图片地址
theGraphics.DrawImage(bmp, new System.Drawing.Rectangle(36, 36, 198, 198),
                    new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.GraphicsUnit.Pixel);


4:在画布画圆。
[C#] 纯文本查看 复制代码
画填充圆:         

Graphics gra = this.pictureBox1.CreateGraphics();

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

Brush bush = new SolidBrush(Color.Green);//填充的颜色


gra.FillEllipse(bush, 10, 10, 100, 100);//画填充椭圆的方法,x坐标、y坐标、宽、高,如果是100,则半径为50

画圆圈:

Graphics gra = this.pictureBox1.CreateGraphics();

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

Pen pen = new Pen(Color.Pink);//画笔颜色                                

gra.DrawEllipse(pen, 250, 10, 100, 100);//画椭圆的方法,x坐标、y坐标、宽、高,如果是100,则半径为50
5:画矩形
[C#] 纯文本查看 复制代码
Rectangle myRectangle = new Rectangle(100, 50, 80, 40);
myGraphics.DrawRectangle(myPen, myRectangle);

6:画线
[C#] 纯文本查看 复制代码
         theGraphics.DrawLine(new Pen(Color.FromArgb(227, 227, 227), 1), 0, Height, 880, Height); //画线

7:文字处理。(我自己写了一个方法,根据参数 去换行自动)
[C#] 纯文本查看 复制代码
    theGraphics.DrawString(str, theFont, newBrush, xwith, yHeight);


8:文字批量换行处理
[C#] 纯文本查看 复制代码

        /// <summary>
        /// 文字处理
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="autoHeight">开始高度</param>
        /// <param name="fontHeight">行高度</param>
        /// <param name="theGraphics">gdp+</param>
        /// <param name="theFontnormal">文字格式</param>
        /// <param name="newBrushnormal">画刷</param>
        /// <para name="kuandu" >宽度</para>
        /// <returns>返回高度</returns>
        public int DrawFont(string strr, int fwith, int autoHeight, int fontHeight, Graphics theGraphics, Font theFontnormal, Brush newBrushnormal, int kuandu)
        {
            strr = strr.Replace(",", "@m@");
            //换行变,号
            strr = strr.Replace("<br/>", ",");

            string[] tag = strr.Split(new char[] { ',' });

            if (tag.Count() > 0)
            {
                foreach (var item in tag)
                {
                    string str = item.Replace("@m@", ",");
                    int thewight = Convert.ToInt16(Fontwigth(str, theFontnormal));
                    if (thewight > kuandu)
                    {
                        int cs = thewight / kuandu;//除数
                        int ys = thewight % kuandu;//余数
                        if (ys > 0)
                        {
                            cs = cs + 1;
                        }
                        int scs = str.Length / (cs - 1);
                        string newstr = string.Empty;

                        for (int i = 0; i < cs; i++)
                        {
                            if (scs > str.Length)
                            {
                                scs = str.Length;
                            }
                            if (Fontwigth(str, theFontnormal) >= kuandu)
                            {
                                do
                                {
                                    newstr = str.Substring(0, scs);
                                    if (Fontwigth(newstr, theFontnormal) > kuandu && scs < 100)
                                    {
                                        scs = scs - 1;
                                    }
                                } while (Fontwigth(newstr, theFontnormal) > kuandu && scs < 100);
                            }
                            else
                            {
                                do
                                {
                                    newstr = str.Substring(0, scs);
                                    if (scs < str.Length)
                                    {
                                        if (Fontwigth(newstr, theFontnormal) < kuandu && scs < 100 && scs < str.Length)
                                        {
                                            scs = scs + 1;
                                        }
                                    }
                                } while (Fontwigth(newstr, theFontnormal) < kuandu && scs < 100 && scs < str.Length);
                            }

                            theGraphics.DrawString(newstr, theFontnormal, newBrushnormal, fwith, autoHeight);
                            autoHeight += fontHeight;
                            if (scs > 0 && str.Length > scs)
                            {
                                str = str.Substring(scs, str.Length - scs);
                            }
                            newstr = string.Empty;
                        }
                    }
                    else
                    {
                        theGraphics.DrawString(str, theFontnormal, newBrushnormal, fwith, autoHeight);
                        autoHeight += fontHeight;
                    }
                }
            }
            return autoHeight;
        }


9:图片流实现图片下载保存
[C#] 纯文本查看 复制代码
 Response.ContentType = "application/x-msdownload";
  //Bitmap theBitmap = new Bitmap(initialWidth, initialHeight);//此为所画的图片
            string filename = "attachment; filename=" +imgname + ".jpg";
            Response.AddHeader("Content-Disposition", filename);
            Response.BinaryWrite(theBitmap);

好了:有了这些准备,一个网页基本上都能画成图片了(这些大家看出来是不是有点像前台设计布局)
还有不完善之处,欢迎大家提宝贵建议。



作者: 站长苏飞    时间: 2016-2-2 10:47
我只是路过打酱油的。
作者: songwenqi    时间: 2016-2-3 08:13
强烈支持楼主ing……
作者: sdaulldd    时间: 2016-2-3 15:26
路过,不错
作者: 菜鸡    时间: 2020-4-15 14:08
你好 看到一下文字批量换行处理的方法 里面有一个Fontwigth方法代码没有  请问是没有贴出来嘛




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4