add text to pic

本文介绍了一个使用 C# 开发的图片批处理应用程序,该应用能够在选定的图片上添加文字水印,并批量处理文件夹内的所有图片。用户可以自定义文字内容、字体样式、颜色、位置等属性。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Drawing.Imaging;

namespace StudySampleCSharp
{
    
/// <summary>
    
/// Form1 の概要の説明です。
    
/// </summary>

    public class Form1 : System.Windows.Forms.Form
    
{
        
private System.Windows.Forms.Label label1;
        
private System.Windows.Forms.Label label2;
        
private System.Windows.Forms.TextBox txtLogo;
        
/// <summary>
        
/// 必要なデザイナ変数です。
        
/// </summary>

        private System.ComponentModel.Container components = null;
        
private System.Windows.Forms.Button btnForeColor;
        
private System.Windows.Forms.Button btnBackColor;        
        
private System.Windows.Forms.Button btnFonts;
        
private System.Windows.Forms.ComboBox cmbPosition;
        
private System.Windows.Forms.Button btnExcute;
        
private System.Windows.Forms.ListBox listBoxFile;
        
private System.Windows.Forms.Button btnSource;
        
private System.Windows.Forms.Button btnDestination;
        
private System.Windows.Forms.TextBox txtDestination;
        
private System.Windows.Forms.TextBox txtSource;

        
private Font titleFont = new Font("MS UI Gothic",9);
        
private Color foreColor = Color.White;
        
private System.Windows.Forms.Label lblDemo;
        
private System.Windows.Forms.PictureBox pictureBoxDemo;
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.TextBox textBox2;
        
private Color backColor = Color.Transparent;

        
public Form1()
        
{
            
//
            
// Windows フォーム デザイナ サポートに必要です。
            
//
            InitializeComponent();

            
//
            
// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
            
//
        }


        
/// <summary>
        
/// 使用されているリソースに後処理を実行します。
        
/// </summary>

        protected override void Dispose( bool disposing )
        
{
            
if( disposing )
            
{
                
if (components != null
                
{
                    components.Dispose();
                }

            }

            
base.Dispose( disposing );
        }


        
Windows フォーム デザイナで生成されたコード

        
/// <summary>
        
/// アプリケーションのメイン エントリ ポイントです。
        
/// </summary>

        [STAThread]
        
static void Main() 
        
{
            Application.Run(
new Form1());
        }


        
private void Form1_Load(object sender, System.EventArgs e)
        
{
            cmbPosition.Items.Add(
"TopLeft");
            cmbPosition.Items.Add(
"TopRight");
            cmbPosition.Items.Add(
"MiddleCenter");
            cmbPosition.Items.Add(
"BottomLeft");
            cmbPosition.Items.Add(
"BottomRight");
            cmbPosition.SelectedIndex 
= 3;
            txtDestination.Text 
= @"C:Documents and Settings84デスクトップpic";
            Demo();
        }


        
private void btnSource_Click(object sender, System.EventArgs e)
        
{
            
string strFileName = "";

            OpenFileDialog fDlg 
= new OpenFileDialog(); 
            fDlg.Multiselect 
= true;
        
            
if (fDlg.ShowDialog() != DialogResult.OK) 
            
{
                
return;
            }


            strFileName 
= fDlg.FileNames[0].ToString();
            txtSource.Text 
= strFileName.Substring(0,strFileName.LastIndexOf("/"));

            
for(int ix=0; ix < fDlg.FileNames.Length; ix++)
            
{
                strFileName 
= fDlg.FileNames[ix].ToString();
                strFileName 
= strFileName.Substring(strFileName.LastIndexOf("/"+ 1);
                listBoxFile.Items.Add(strFileName);
            }


            fDlg.Dispose();
        }

        
private void btnDestination_Click(object sender, System.EventArgs e)
        
{
            FolderBrowserDialog foldDlg 
= new FolderBrowserDialog(); 
            
if (foldDlg.ShowDialog() != DialogResult.OK) 
            
{
                
return;
            }

            txtDestination.Text 
= foldDlg.SelectedPath;
        
        }

        
private void listBoxFile_SelectedIndexChanged(object sender, System.EventArgs e)
        
{
            
string strFilePath;
            
if (listBoxFile.SelectedIndex < 0)
            
{
                
return;
            }


            strFilePath 
= txtSource.Text + "/" + listBoxFile.Items[listBoxFile.SelectedIndex];
            
if (File.Exists(strFilePath))
            
{
                Image img 
= Image.FromFile(strFilePath);
                pictureBoxDemo.Image 
= img;
                img.Dispose();
            }

        }


        
private void btnFonts_Click(object sender, System.EventArgs e)
        
{

            FontDialog fontDlg 
= new FontDialog();
            fontDlg.Font 
= titleFont;
            
if (fontDlg.ShowDialog()!= DialogResult.OK)
            
{
                
return;
            }


            titleFont 
= fontDlg.Font;
            fontDlg.Dispose();
            Demo();
        }


        
private void btnForeColor_Click(object sender, System.EventArgs e)
        
{
            ColorDialog colorDlg 
= new ColorDialog();
            colorDlg.Color 
= foreColor;
            
if (colorDlg.ShowDialog()!= DialogResult.OK)
            
{
                
return;
            }


            foreColor 
= colorDlg.Color;
            colorDlg.Dispose();
            Demo();
        }


        
private void btnBackColor_Click(object sender, System.EventArgs e)
        
{
            ColorDialog colorDlg 
= new ColorDialog();
            colorDlg.Color 
= backColor;
            
if (colorDlg.ShowDialog()!= DialogResult.OK)
            
{
                
return;
            }


            backColor 
= colorDlg.Color;    
            colorDlg.Dispose();
            Demo();
        }

        
        
private void btnExcute_Click(object sender, System.EventArgs e)
        
{            
            
string strLogoTitle = txtLogo.Text;
            
if (strLogoTitle == string.Empty)
            
{
                MessageBox.Show(
"The LogoTitle can't be empty!");
                txtLogo.Focus();
                
return;
            }

            
if (listBoxFile.Items.Count < 1)
            
{
                MessageBox.Show(
"Please set the files that you want to add title to!");
                
return;
            }


            
if (txtDestination.Text == string.Empty)
            
{
                MessageBox.Show(
"Please set the destination fold that you want to save the images!");
                
return;
            }


            
string fileName = "";
            
string FILE_NAME = "";
            System.Drawing.Image image;
            Bitmap bitmap;
            Graphics g;

            
float rectX;        
            
float rectY;
            
float rectWidth = strLogoTitle.Length*(titleFont.Size+8);
            
float rectHeight = titleFont.Size+8;                        
                
            Brush frontBrush 
= new SolidBrush(foreColor);
            Brush backBrush 
= new SolidBrush(backColor);    

            
for (int ix = 0; ix < listBoxFile.Items.Count; ix++)
            
{
                fileName 
= txtSource.Text + "/";
                fileName 
= fileName + listBoxFile.Items[ix].ToString();

                
if(!File.Exists(fileName))
                
{
                    
continue;
                }

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

                
switch(cmbPosition.SelectedIndex)
                
{
                    
case 0:
                        rectX 
= 0;
                        rectY 
= 0;
                        
break;
                    
case 1:
                        rectX 
= image.Width - titleFont.Size * txtLogo.Text.Length;
                        rectY 
= 0;
                        
break;
                    
case 2:
                        rectX 
= image.Width / 2;
                        rectY 
= image.Height / 2;
                        
break;
                    
case 3:
                        rectX 
= 0;
                        rectY 
= image.Height - titleFont.Size;
                        
break;
                    
case 4:
                        rectX 
= image.Width - titleFont.Size * txtLogo.Text.Length;
                        rectY 
= image.Height - titleFont.Size;
                        
break;
                    
default:
                        rectX 
= 0;
                        rectY 
= image.Height - titleFont.Size;
                        
break;
                }


                RectangleF textArea 
= new RectangleF(rectX,rectY,rectWidth,rectHeight);    
                g.FillRectangle(backBrush,rectX,rectY,rectWidth,rectHeight); 
                g.DrawString(strLogoTitle,titleFont,frontBrush,textArea);

                FILE_NAME 
= txtDestination.Text + "/";
                FILE_NAME 
= FILE_NAME + listBoxFile.Items[ix].ToString();
                bitmap.Save(FILE_NAME,ImageFormat.Jpeg);
                g.Dispose();
                bitmap.Dispose();
                image.Dispose();
            }


            MessageBox.Show(
"complete!");
        }


        
private void Demo()
        
{
            
int iGood = 2;
            lblDemo.Text 
= txtLogo.Text;
            lblDemo.Width 
= 100;
            lblDemo.Height 
= 24;
            lblDemo.BackColor 
= backColor;
            lblDemo.ForeColor  
= foreColor;
            lblDemo.Font 
= titleFont;
            
switch(cmbPosition.SelectedIndex)
            
{
                
case 0:
                    lblDemo.Left 
= pictureBoxDemo.Left + iGood;
                    lblDemo.Top 
= pictureBoxDemo.Top + iGood;
                    
break;
                
case 1:
                    lblDemo.Left 
= pictureBoxDemo.Left + pictureBoxDemo.Width - lblDemo.Width - iGood;
                    lblDemo.Top 
= pictureBoxDemo.Top + iGood;
                    
break;
                
case 2:
                    lblDemo.Left 
= pictureBoxDemo.Left + pictureBoxDemo.Width / 2 - lblDemo.Width / 2;
                    lblDemo.Top 
= pictureBoxDemo.Top + pictureBoxDemo.Height / 2 - lblDemo.Height / 2;
                    
break;
                
case 3:
                    lblDemo.Left 
= pictureBoxDemo.Left + iGood;
                    lblDemo.Top 
= pictureBoxDemo.Top + pictureBoxDemo.Height - lblDemo.Height - iGood;
                    
break;
                
case 4:
                    lblDemo.Left 
= pictureBoxDemo.Left + pictureBoxDemo.Width - lblDemo.Width - iGood;
                    lblDemo.Top 
= pictureBoxDemo.Top + pictureBoxDemo.Height - lblDemo.Height - iGood;
                    
break;
                
default:
                    lblDemo.Left 
= pictureBoxDemo.Left + iGood;
                    lblDemo.Top 
= pictureBoxDemo.Top + pictureBoxDemo.Height - lblDemo.Height - iGood;
                    
break;
            }

            
        }


        
private void cmbPosition_SelectedIndexChanged(object sender, System.EventArgs e)
        
{
            Demo();        
        }


        
private void txtLogo_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        
{
            Demo();
        }

    }

}

 
import pandas as pd from docx import Document from docx.shared import Cm import os import re def main(): # 设置路径 excel_path = r'C:\Users\Administrator\Desktop\threeone\model.xls' template_path = r'C:\Users\Administrator\Desktop\threeone\Btype.doc' pic_folder = r'C:\Users\Administrator\Desktop\threeone\pic' output_folder = r'C:\Users\Administrator\Desktop\threeone\model' # 创建输出目录(如果不存在) os.makedirs(output_folder, exist_ok=True) try: # 读取Excel数据 df = pd.read_excel( excel_path, sheet_name='置换恢复', usecols='A:C', # 只读取A、B、C列 header=1, # 从第2行开始读取(索引从0开始) names=['A列', 'B列', 'C列'] # 指定列名 ) # 加载Word模板 doc = Document(template_path) # 处理每一行数据 for _, row in df.iterrows(): # 创建文档副本 new_doc = Document(template_path) filename = str(row['A列']).strip() # 替换文本内容 replacements = { 'AA': str(row['A列']), 'BB': str(row['B列']), 'CC': str(row['C列']) } for paragraph in new_doc.paragraphs: for key, value in replacements.items(): if key in paragraph.text: paragraph.text = paragraph.text.replace(key, value) # 插入图片 pic_extensions = ['.jpg', '.jpeg', '.png', '.bmp'] pic_found = False for ext in pic_extensions: pic_path = os.path.join(pic_folder, f"{filename}{ext}") if os.path.exists(pic_path): # 在所有段落中查找DD占位符 for paragraph in new_doc.paragraphs: if 'DD' in paragraph.text: paragraph.text = paragraph.text.replace('DD', '') run = paragraph.add_run() run.add_picture(pic_path, height=Cm(10)) pic_found = True break if pic_found: break # 清理文件名中的非法字符 safe_filename = re.sub(r'[\\/*?:"<>|]', '', filename) output_path = os.path.join(output_folder, f"{safe_filename}.docx") # 保存文档 new_doc.save(output_path) print(f"已创建文档: {output_path}") except Exception as e: print(f"处理过程中出错: {str(e)}") if __name__ == "__main__": main() 处理过程中出错: Package not found at 'C:\Users\Administrator\Desktop\threeone\Btype.doc'
11-15
from pptx import Presentation from pptx.util import Inches, Pt from pptx.dml.color import RGBColor from pptx.enum.text import PP_ALIGN # 创建空白PPT prs = Presentation() # ---------------------- 第1页:封面 ---------------------- slide1 = prs.slides.add_slide(prs.slide_layouts[6]) # 空白版式 # 标题文本框 title_box = slide1.shapes.add_textbox(Inches(1), Inches(1.5), Inches(8), Inches(1)) title_frame = title_box.text_frame title_para = title_frame.add_paragraph() title_para.text = "祖国大好河山" title_para.font.name = "宋体" title_para.font.size = Pt(44) title_para.font.bold = True title_para.alignment = PP_ALIGN.CENTER # 姓名日期文本框(左对齐,间距杂乱) info_box = slide1.shapes.add_textbox(Inches(0.5), Inches(4), Inches(3), Inches(1)) info_frame = info_box.text_frame info_para1 = info_frame.add_paragraph() info_para1.text = "姓名:XXX" info_para1.font.name = "宋体" info_para1.font.size = Pt(20) info_para1.alignment = PP_ALIGN.LEFT info_para2 = info_frame.add_paragraph() info_para2.text = "日期:XXXX年XX月" info_para2.font.name = "宋体" info_para2.font.size = Pt(20) info_para2.alignment = PP_ALIGN.LEFT info_para2.space_after = Pt(15) # 刻意弄乱行距 # ---------------------- 第2页:长城 ---------------------- slide2 = prs.slides.add_slide(prs.slide_layouts[6]) # 插入长城图(左偏,轻微拉伸,替换为你的图片路径) img_path1 = "changcheng.jpg" # 本地图片路径,自行替换 slide2.shapes.add_picture(img_path1, Inches(0.2), Inches(0.5), width=Inches(4.5), height=Inches(5)) # 右侧文字(行距不一致) text_box1 = slide2.shapes.add_textbox(Inches(5), Inches(1), Inches(4.5), Inches(4)) text_frame1 = text_box1.text_frame para1 = text_frame1.add_paragraph() para1.text = "长城主要在我国北京、河北等地" para1.font.name = "宋体" para1.font.size = Pt(18) para1.alignment = PP_ALIGN.LEFT para2 = text_frame1.add_paragraph() para2.text = "它是古代用来防御的建筑,长度特别长" para2.font.name = "宋体" para2.font.size = Pt(18) para2.alignment = PP_ALIGN.LEFT para2.space_before = Pt(8) para3 = text_frame1.add_paragraph() para3.text = "每年都有很多游客去爬长城、看风景" para3.font.name = "宋体" para3.font.size = Pt(18) para3.alignment = PP_ALIGN.LEFT para3.space_before = Pt(15) # ---------------------- 第3页:黄山 ---------------------- slide3 = prs.slides.add_slide(prs.slide_layouts[6]) # 插入黄山图(右偏,偏小,替换图片路径) img_path2 = "huangshan.jpg" slide3.shapes.add_picture(img_path2, Inches(5), Inches(0.8), width=Inches(4), height=Inches(4)) # 下方文字 text_box2 = slide3.shapes.add_textbox(Inches(1), Inches(4.8), Inches(8), Inches(1)) text_frame2 = text_box2.text_frame para4 = text_frame2.add_paragraph() para4.text = "黄山位于安徽黄山风景区" para4.font.name = "宋体" para4.font.size = Pt(18) para4.alignment = PP_ALIGN.CENTER para5 = text_frame2.add_paragraph() para5.text = "山上有奇松、怪石、云海,看着很壮观" para5.font.name = "宋体" para5.font.size = Pt(18) para5.alignment = PP_ALIGN.CENTER # ---------------------- 第4页:西湖 ---------------------- slide4 = prs.slides.add_slide(prs.slide_layouts[6]) # 插入西湖图(偏大,略右歪) img_path3 = "xihu.jpg" slide4.shapes.add_picture(img_path3, Inches(0.1), Inches(1.8), width=Inches(9.8), height=Inches(4)) # 上方文字(有多余空格) text_box3 = slide3.shapes.add_textbox(Inches(0.5), Inches(0.5), Inches(8), Inches(1)) text_frame3 = text_box3.text_frame para6 = text_frame3.add_paragraph() para6.text = " 西湖在浙江杭州,是很有名的淡水湖" # 开头多余空格 para6.font.name = "宋体" para6.font.size = Pt(18) para6.alignment = PP_ALIGN.LEFT para7 = text_frame3.add_paragraph() para7.text = "湖边有柳树、亭子,湖水很清澈" para7.font.name = "宋体" para7.font.size = Pt(18) para7.alignment = PP_ALIGN.LEFT # ---------------------- 第5页:桂林山水 ---------------------- slide5 = prs.slides.add_slide(prs.slide_layouts[6]) # 插入桂林图(底部截断,偏下) img_path4 = "guilin.jpg" slide5.shapes.add_picture(img_path4, Inches(0.5), Inches(2), width=Inches(9), height=Inches(4.5)) # 底部超出页面 # 上方文字(右对齐) text_box4 = slide5.shapes.add_textbox(Inches(2), Inches(0.5), Inches(7), Inches(1)) text_frame4 = text_box4.text_frame para8 = text_frame4.add_paragraph() para8.text = "桂林在广西壮族自治区" para8.font.name = "宋体" para8.font.size = Pt(18) para8.alignment = PP_ALIGN.RIGHT para9 = text_frame4.add_paragraph() para9.text = "山水秀丽,坐船游河能看到很多好看的景色" para9.font.name = "宋体" para9.font.size = Pt(18) para9.alignment = PP_ALIGN.RIGHT # ---------------------- 第6页:结尾 ---------------------- slide6 = prs.slides.add_slide(prs.slide_layouts[6]) # 结尾文字(轻微左偏) end_box = slide6.shapes.add_textbox(Inches(0.8), Inches(2), Inches(8.5), Inches(1)) end_frame = end_box.text_frame end_para = end_frame.add_paragraph() end_para.text = "祖国风景很美,谢谢观看" end_para.font.name = "宋体" end_para.font.size = Pt(36) end_para.font.bold = True end_para.alignment = PP_ALIGN.CENTER # 保存PPT prs.save("祖国大好河山.pptx") print("PPT生成完成,已保存为【祖国大好河山.pptx】")
11-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值