在图像上绘制文本库

3
有没有C#中的绘制文本到图像的开源库?我一整天都在尝试使用TextRenderer和graphics.DrawString(),但我从未接近过得到体面结果,我尝试了每种平滑、插值、TextRenderHint的组合,但质量总是半好不坏。
以下是一些我所实现的最佳图像:
https://istack.dev59.com/8CyyC.webp 它需要看起来像这样:
https://istack.dev59.com/fxkQ9.webp 这个真的很好看,但有些字符串似乎字符间距不正确,某些字母倾斜。
设置如下:
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
              objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
              objGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.GammaCorrected;
              objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
              objGraphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
              objGraphics.TextContrast = 0;

格式为Png,背景透明,方法是TextRenderer.Drawtext()。似乎文本的粗细出了问题,我猜测是平滑处理有问题,当我试图加粗文本时,它几乎没有变化,但只有在字体大小约为10px时才会出现。


你在使用Winforms吗?你的目标是哪个版本的.NET? - ose
我实际上正在使用ASP.NET 4.0。 - formatc
我已经为您的帖子添加了ASP.NET标签。将来这样做将使您的问题更容易被具有ASP.NET专业知识的人看到。 - ose
展示一下你尝试过的内容。你可以使用Graphics.DrawString、Fonts、Brushes等工具在图像上绘制出优秀的文本。 - Trevor Elliott
@ose 谢谢。我忘记打标签了。 - formatc
你有看过这个吗?http://www.codeproject.com/Articles/1827/Web-Graphics-On-The-Fly-in-ASP-NET - Aristos
2个回答

8
以下是我用于在上传到我的网站上的照片上添加版权水印的方法:
    //Add Watermark to photo.
    private System.Drawing.Image CreateWatermark(System.Drawing.Image imgPhoto, string Copyright)
    {
        Graphics g = Graphics.FromImage(imgPhoto);

        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        foreach (PropertyItem pItem in imgPhoto.PropertyItems)
        {
            imgPhoto.SetPropertyItem(pItem);
        }

        int phWidth = imgPhoto.Width;
        int phHeight = imgPhoto.Height;

        //create a Bitmap the Size of the original photograph
        Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        //load the Bitmap into a Graphics object 
        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        //------------------------------------------------------------
        //Step #1 - Insert Copyright message
        //------------------------------------------------------------

        //Set the rendering quality for this Graphics object
        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

        //Draws the photo Image object at original size to the graphics object.
        grPhoto.DrawImage(
            imgPhoto,                               // Photo Image object
            new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
            0,                                      // x-coordinate of the portion of the source image to draw. 
            0,                                      // y-coordinate of the portion of the source image to draw. 
            phWidth,                                // Width of the portion of the source image to draw. 
            phHeight,                               // Height of the portion of the source image to draw. 
            GraphicsUnit.Pixel);                    // Units of measure 

        //-------------------------------------------------------
        //to maximize the size of the Copyright message we will 
        //test multiple Font sizes to determine the largest posible 
        //font we can use for the width of the Photograph
        //define an array of point sizes you would like to consider as possiblities
        //-------------------------------------------------------
        int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

        Font crFont = null;
        SizeF crSize = new SizeF();

        //Loop through the defined sizes checking the length of the Copyright string
        //If its length in pixles is less then the image width choose this Font size.
        for (int i = 0; i < 7; i++)
        {
            //set a Font object to Arial (i)pt, Bold
            crFont = new Font("arial", sizes[i], FontStyle.Bold);
            //Measure the Copyright string in this Font
            crSize = grPhoto.MeasureString(Copyright, crFont);

            if ((ushort)crSize.Width < (ushort)phWidth)
                break;
        }

        //Since all photographs will have varying heights, determine a 
        //position 5% from the bottom of the image
        int yPixlesFromBottom = (int)(phHeight * .05);

        //Now that we have a point size use the Copyrights string height 
        //to determine a y-coordinate to draw the string of the photograph
        float yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));

        //Determine its x-coordinate by calculating the center of the width of the image
        float xCenterOfImg = (phWidth / 2);

        //Define the text layout by setting the text alignment to centered
        StringFormat StrFormat = new StringFormat();
        StrFormat.Alignment = StringAlignment.Near;

        //define a Brush which is semi trasparent black (Alpha set to 153)
        SolidBrush semiTransBrush2 = new SolidBrush(System.Drawing.Color.FromArgb(153, 0, 0, 0));

        //Draw the Copyright string
        grPhoto.DrawString(Copyright,                 //string of text
            crFont,                                   //font
            semiTransBrush2,                           //Brush
            new PointF(xCenterOfImg + 1, yPosFromBottom + 1),  //Position
            StrFormat);

        //define a Brush which is semi trasparent white (Alpha set to 153)
        SolidBrush semiTransBrush = new SolidBrush(System.Drawing.Color.FromArgb(153, 255, 255, 255));

        //Draw the Copyright string a second time to create a shadow effect
        //Make sure to move this text 1 pixel to the right and down 1 pixel
        grPhoto.DrawString(Copyright,                 //string of text
            crFont,                                   //font
            semiTransBrush,                           //Brush
            new PointF(xCenterOfImg, yPosFromBottom),  //Position
            StrFormat);                               //Text alignment
        imgPhoto = bmPhoto;
        return imgPhoto;
    }

1
谢谢,初看起来真的很不错!无论如何,我找到了解决方案。我的问题是我在透明背景上绘制文本,而当用任何背景颜色填充时就解决了。但是查看这段代码可能会解决我可能遇到的更多问题。 - formatc

1

在ASP.NET中使用System.Drawing类是不受支持的。

具体而言,如果您在多个线程负载下使用它,您将遇到像这样的异常:

Win32Exception: The operation completed successfully
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y,     Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Media.MediaContextNotificationWindow..ctor(MediaContext ownerMediaContext)
at System.Windows.Media.MediaContext..ctor(Dispatcher dispatcher)

话虽如此,我们发现将所有绘图操作调度到单个STA线程似乎可以避免这些问题。

更新:已经过去五年了,我们仍然没有使用这种方法遇到任何问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接