繁体   English   中英

从C#中的多行字符串创建自动调整大小的图像(png)

[英]Creating autosized image (png) from multi-line string in C#

我正在尝试从用户输入的文本创建图像。 最终,它将被用于发送状态更新到Twitter。

我无法控制用户文字的长度-它是可变的。

最初,我能够使用System.Drawing DrawString方法从文本中绘制png,但是输出是宽度可能很大的单行png-显然这不是可行的解决方案。

我有一个想法可以将字符串分成多个长度,并分别在png中绘制它们,这是可行的,但是由于它包裹了中间单词,因此感觉并不优雅,而且我不能保证它可以与长字符串一起使用(如果钉刺长度的25%仍然太宽而无法容纳png)。 总而言之,它比我原来的解决方案要好,但长期来看仍然不可行。

这是我用来创建png的代码:

string quoteText = someString; //my user's input text
int strLength = quoteText.Length;
        int i25 = strLength / 4;
        string st25 = quoteText.Substring(0, i25);
        string st50 = quoteText.Substring(i25 + 1, i25);
        string st75 = quoteText.Substring((i25 * 2) + 1, i25);
        string st100 = quoteText.Substring((i25 * 3) + 1);


        Bitmap objBmpImage = new Bitmap(500, 600);

        int intWidth = 600;
        int intHeight = 700;

        // Create the Font object for the image text drawing.
        Font objFont = new Font("Roboto Condensed", 14, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
        Font brandFont = new Font("IM Fell Double Pica", 14, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Pixel);

        // Create a graphics object to measure the text's width and height.
        Graphics objGraphics = Graphics.FromImage(objBmpImage);

        // This is where the bitmap size is determined.
        intWidth = 500;
        intHeight = 600;


        // Create the bmpImage again with the correct size for the text and font.
        objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));

        // Add the colors to the new bitmap.
        objGraphics = Graphics.FromImage(objBmpImage);

        // Set Background color
        objGraphics.Clear(Color.White);
        objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
        objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
        objGraphics.DrawString(st25, objFont, new SolidBrush(Color.FromArgb(0, 126, 58)), 0, 0);
        objGraphics.DrawString(st50, objFont, new SolidBrush(Color.FromArgb(0, 126, 58)), 0, 30);
        objGraphics.DrawString(st75, objFont, new SolidBrush(Color.FromArgb(0, 126, 58)), 0, 60);
        objGraphics.DrawString(st100, objFont, new SolidBrush(Color.FromArgb(0, 126, 58)), 0, 90);
        objGraphics.DrawString("some site branding", brandFont, new SolidBrush(Color.FromArgb(0, 126, 58)), 100, 120);

        objGraphics.Flush();


        //create the path for the imge to be saved
        string imagePath = System.Web.HttpContext.Current.Server.MapPath("~/MyServerPath/" + sURL + ".png");
        objBmpImage.Save(imagePath);

        //return the imagePath
        return imagePath;

谁能建议一种更动态地创建png高度和宽度的方法,以适合于字符串的长度,并优雅地进行包装(在分词处)?

我已经进行了多次搜索,但找不到能完全满足我要求的内容。

您应该查看Graphics.MeasureString,此方法允许您以像素为单位测量给定字体中特定字符串的宽度和高度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM