加载中…
个人资料
狮子座小小羊
狮子座小小羊
  • 博客等级:
  • 博客积分:0
  • 博客访问:109,617
  • 关注人气:5
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

指定图片添加文字(C#)

(2013-10-31 22:31:37)
标签:

图片

文字

图片添加文字

it

分类: .net(c#)

    /// <summary>
    /// 指定图片添加指定文字
    /// </summary>
    /// <param name="fileName">指定文件路径</param>
    /// <param name="text">添加的文字</param>
    /// <param name="picname">生成文件名</param>

    private void AddTextToImg(string fileName, string text,string picname)
    {
        //判断指定图片是否存在
        if (!File.Exists(MapPath(fileName)))
        {
            throw new FileNotFoundException("The file don't exist!");
        }

        if (text == string.Empty)
        {
            return;
        }
       

        System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(fileName));
        Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
        Graphics g = Graphics.FromImage(bitmap);

        float fontSize = 40.0f;             //字体大小
        float textWidth = text.Length * fontSize;  //文本的长度
        //下面定义一个矩形区域,以后在这个矩形里画上白底黑字
        float rectX = 120;
        float rectY = 200;
        float rectWidth = text.Length * (fontSize + 40);
        float rectHeight = fontSize + 40;
        //声明矩形域
        RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);

        Font font = new Font("微软雅黑", fontSize,FontStyle.Bold );   //定义字体
        //font.Bold = true;

        Brush whiteBrush = new SolidBrush(Color.DodgerBlue);   //白笔刷,画文字用
        //Brush blackBrush = new SolidBrush(Color.Black);   //黑笔刷,画背景用

        //g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);

        g.DrawString(text, font, whiteBrush, textArea);
        MemoryStream ms = new MemoryStream();

        //输出方法一:将文件生成并保存到C盘
        string path = "C:\\" + picname + ".gif";
        bitmap.Save(path , System.Drawing.Imaging.ImageFormat.Gif);


        //输出方法二,显示在网页中,保存为Jpg类型
        //bitmap.Save(ms, ImageFormat.Jpeg);
        //Response.Clear();
        //Response.ContentType = "image/jpeg";
        //Response.BinaryWrite(ms.ToArray());

        g.Dispose();
        bitmap.Dispose();
        image.Dispose();
 }

 

//调用

protected void Page_Load(object sender, EventArgs e)
    {
       AddTextToImg("testPic.jpg", "图片测试","test");
    }

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有