最近做項目需要動態給圖片增加文字(書本的封面圖片),修改字型大小、字型、顏色、控制位置等,下面通過執行個體代碼給大家分享C#在圖片增加文字的實現代碼,一起看看吧
業務需要動態給圖片增加文字(書本的封面圖片),修改字型大小、字型、顏色、控制位置
測試代碼:
string path = @"E:\cover.png"; Bitmap bmp = new Bitmap(path); Graphics g = Graphics.FromImage(bmp); String str = "賢愚經"; Font font = new Font("仿宋_GB2312", 14, FontStyle.Bold);//設定字型,大小,粗細 SolidBrush sbrush = new SolidBrush(Color.White);//設定顏色 int base_left = 10; int left_space = 30; int base_top = 27; int top_space = 27; for (int i = 0; i < str.Length; i++) { if (i > 13) { continue; g.DrawString(str[i] + "", font, sbrush, new PointF(base_left + (left_space * 2), base_top + (top_space * (i - 14)))); } else if (i > 6) { g.DrawString(str[i] + "", font, sbrush, new PointF(base_left + (left_space * 1), base_top + (top_space * (i - 7)))); } else { g.DrawString(str[i] + "", font, sbrush, new PointF(base_left, base_top + (top_space * i))); } } //MemoryStream ms = new MemoryStream(); //bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); bmp.Save(@"E:\cover1.png");
字型選擇:
黑體:SimHei
宋體:SimSun
新宋體:NSimSun
仿宋:FangSong
楷體:KaiTi
仿宋_GB2312:FangSong_GB2312
楷體_GB2312:KaiTi_GB2312
微軟雅黑體:Microsoft YaHei