C#指定图片添加文字

12 篇文章 0 订阅
using System.Drawing;
using System.IO;
using UnityEngine;

public class TestImage : MonoBehaviour
{
    private string filePath;
    // Use this for initialization
    void Start()
    {
        filePath = @Application.streamingAssetsPath + "/test.jpg";
        AddTextToImg("卧槽啊!小贱!");
    }

    // Update is called once per frame
    void Update()
    {

    }

    /// <summary>
    /// 指定图片添加指定文字
    /// </summary> 
    /// <param name="text">添加的文字</param>
    /// <param name="picname">生成文件名</param>
    private void AddTextToImg(string text)
    {
        //判断指定图片是否存在
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException("The file don't exist!");
        }
        if (text == string.Empty)
        {
            return;
        } 
        Image image = Image.FromFile(filePath);
        Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
        System.Drawing.Graphics g = System.Drawing.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);
        //定义字体
        System.Drawing.Font font = new System.Drawing.Font("微软雅黑", fontSize, System.Drawing.FontStyle.Bold);
        //font.Bold = true;
        //白笔刷,画文字用
        Brush whiteBrush = new SolidBrush(System.Drawing.Color.DodgerBlue);   
        //黑笔刷,画背景用
        //Brush blackBrush = new SolidBrush(Color.Black);   
        //g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
        g.DrawString(text, font, whiteBrush, textArea); 
        //输出方法一:将文件生成并保存到C盘
        string path = @Application.streamingAssetsPath + "/test2.jpg";
        bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); 
        g.Dispose();
        bitmap.Dispose();
        image.Dispose();
    }
}



原文点击这里

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值