将文本文件的内容或者文字保存成图片的方法分享
程序员文章站
2024-02-27 17:38:03
调用方法:复制代码 代码如下:converttextfiletoimage(server.mappath("~/log.txt"),server.mappath("~/lo...
调用方法:
复制代码 代码如下:
converttextfiletoimage(server.mappath("~/log.txt"),server.mappath("~/log.png"));
实现代码:
复制代码 代码如下:
void converttextfiletoimage(string textfile,string imagefile)
{
system.drawing.font drawfont = new system.drawing.font("宋体", 12);
system.drawing.bitmap image = new system.drawing.bitmap(1, 1);
system.drawing.graphics g = system.drawing.graphics.fromimage(image);
string text = system.io.file.readalltext(textfile, encoding.getencoding("gb2312"));
system.drawing.sizef sf = g.measurestring(text, drawfont, 1024); //设置一个显示的宽度
image = new system.drawing.bitmap(image, new system.drawing.size(convert.toint32(sf.width), convert.toint32(sf.height)));
g = system.drawing.graphics.fromimage(image);
g.clear(system.drawing.color.white);
g.textrenderinghint = system.drawing.text.textrenderinghint.antialiasgridfit;
g.drawstring(text, drawfont, system.drawing.brushes.black, new system.drawing.rectanglef(new system.drawing.pointf(0, 0), sf));
image.save(imagefile, system.drawing.imaging.imageformat.png);
g.dispose();
image.dispose();
}