2015/11/09

C#.Net 圖片加上文字

Code:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace ImageAddFont
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 背景圖
        /// </summary>
        private Bitmap bitmapBack;
        
        /// <summary>
        /// 文字
        /// </summary>
        private String text
        {
            get { return textBox1.Text; }
        }

        /// <summary>
        /// 字體大小
        /// </summary>
        private const int FONT_SIZE = 100;

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonMark_MouseClick(object sender, MouseEventArgs e)
        {
            if (!text.Equals(String.Empty))
            {
                if (bitmapBack != null)
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter = "JPG File|*.jpg";

                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        Graphics g = Graphics.FromImage(bitmapBack);
                        RectangleF rectF = new RectangleF(0, 0, text.Length * FONT_SIZE, (int)(FONT_SIZE/0.35));
                        g.DrawString(text, new Font("Tahoma", FONT_SIZE), Brushes.Blue, rectF);
                        g.Flush();
                        bitmapBack.Save(dialog.FileName);
                        MessageBox.Show("製作成功");
                    }
                }else
                    MessageBox.Show("請選擇背景圖");
            }
            else
                MessageBox.Show("請輸入文字");

        }

        private void buttonImage_MouseClick(object sender, MouseEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "JPG File|*.jpg";

            if (dialog.ShowDialog() == DialogResult.OK)
                bitmapBack = new Bitmap(dialog.FileName);
        }


    }
}


執行前:



執行後: