【发布时间】:2019-01-18 15:42:23
【问题描述】:
在 winform 应用程序中,我将字符串转换为 Image 并希望保存一个 txt 文件。其中(txt 文件)文本被格式化为图像。
这是将字符串转换为图像的代码=>
private void DrawText(string text)
{
textBox2.SelectAll();
FontColor = Color.Black;
FontBackColor =Color.White;
FontName = "LinoScript";// richTextBox1.SelectionFont.Name;
FontSize = 24; //Convert.ToInt16(richTextBox1.SelectionFont.Size);
ImageHeight = 2630;
ImageWidth = 1599;
ImagePath = textBox1.Text.Trim() + numericUpDown1.Value.ToString()+".JPEG";
// ImagePath = @"D:\Test.JPEG"; //give the file name you want to export to as image
ImageText = new Bitmap(ImageWidth, ImageHeight);
ImageText.SetResolution(90,100);
ImageGraphics = Graphics.FromImage(ImageText);
MarginsBox m = new MarginsBox();
// printmap.SetResolution(dpi, dpi); // Set the resolution of our paper
m.Top = 1 * 95; // Set a 1' margin, from the top
m.Left = 1.25f * 95; // Set a 1.25' margin, from the left
m.Bottom = ImageText.Height - m.Top; // 1', from the bottom
m.Right = ImageText.Width - m.Left; // 1.25', from the right
m.Width = ImageText.Width - (m.Left * 2); // Get the width of our working area
m.Height = ImageText.Height - (m.Top * 2); // Get the height of our working area
ImageFont = new Font(FontName, FontSize);
ImagePointF = new PointF(5, 5);
BrushForeColor = new SolidBrush(FontColor);
BrushBackColor = new SolidBrush(Color.White);
StringFormat drawFormat = new StringFormat();
ImageGraphics.FillRectangle(BrushBackColor, 0, 0, ImageWidth,ImageHeight);
//ImageGraphics.DrawString(text, ImageFont, BrushForeColor, ImagePointF);
ImageGraphics.DrawString(text, ImageFont, BrushForeColor, new RectangleF(m.Left, m.Top, m.Width, m.Height),drawFormat);
SaveMyFile(text);
//Draw a byte and create image file
string outputFileName = ImagePath;
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
ImageText.Save(memory, ImageFormat.Gif);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
}
我正在创建这样的文本文件:
public void SaveMyFile(string datastring)
{
StringFormat drawFormat = new StringFormat();
TextWriter writer = new StreamWriter(@textBox1.Text.Trim() + numericUpDown1.Value.ToString() + "image.txt");
writer.Write(datastring, drawFormat);
writer.Close();
}
我想要 .txt 文件,其中的文本格式应该像生成的图像。
我想要一个 .txt 文件,其中的文本应该像图像中那样逐行显示。
提前致谢
【问题讨论】:
-
您的问题是什么?你被困在哪里了?请阅读how-to-ask,因为您似乎在要求某人编写您的代码——这与本网站的主题无关。
-
@nilsk 我想要一个 txt 文件,其中的文本应该像图像一样逐行排列...
-
您的意思是希望 txt 文件具有与图像中相同的字体、字体大小和边距?如果是这样,这在 txt 文件中是不可能的。 txt 文件不能设置其格式。您可以使用富文本文件 (.rtf) 或类似文件来执行此操作。在 txt 文件中可以做什么和不可以做什么:computerhope.com/issues/ch001872.htm
-
@gunnerone ..如果我将文件格式更改为 .rtf 那么这可能吗...如果可能请告诉我..如何???