1. 程式人生 > >C#指定圖片新增文字

C#指定圖片新增文字

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();
    }
}