web-dev-qa-db-ja.com

実行時にオンザフライでテキストから画像を生成する方法

誰でも入力テキストから画像を生成する方法をガイドできますか。画像には拡張子は関係ありません。

59
Ravia

OK、C#で画像に文字列を描画する場合、ここでSystem.Drawing名前空間を使用する必要があります。

private Image DrawText(String text, Font font, Color textColor, Color backColor)
{
    //first, create a dummy bitmap just to get a graphics object
    Image img = new Bitmap(1, 1);
    Graphics drawing = Graphics.FromImage(img);

    //measure the string to see how big the image needs to be
    SizeF textSize = drawing.MeasureString(text, font);

    //free up the dummy image and old graphics object
    img.Dispose();
    drawing.Dispose();

    //create a new image of the right size
    img = new Bitmap((int) textSize.Width, (int)textSize.Height);

    drawing = Graphics.FromImage(img);

    //Paint the background
    drawing.Clear(backColor);

    //create a brush for the text
    Brush textBrush = new SolidBrush(textColor);

    drawing.DrawString(text, font, textBrush, 0, 0);

    drawing.Save();

    textBrush.Dispose();
    drawing.Dispose();

    return img;

}

このコードは最初に文字列を測定し、次に正しいサイズの画像を作成します。

この関数の戻り値を保存する場合は、返された画像のSaveメソッドを呼び出すだけです。

148
Kazar

ありがとうカザール。使用後の画像/グラフィックオブジェクトの廃棄にUSINGを使用し、最小サイズのパラメーターを導入するという以前の回答のわずかな改善

    private Image DrawTextImage(String currencyCode, Font font, Color textColor, Color backColor) {
        return DrawTextImage(currencyCode, font, textColor, backColor, Size.Empty);
    }
    private Image DrawTextImage(String currencyCode, Font font, Color textColor, Color backColor, Size minSize) {
        //first, create a dummy bitmap just to get a graphics object
        SizeF textSize;
        using (Image img = new Bitmap(1, 1)) {
            using (Graphics drawing = Graphics.FromImage(img)) {
                //measure the string to see how big the image needs to be
                textSize = drawing.MeasureString(currencyCode, font);
                if (!minSize.IsEmpty) {
                    textSize.Width = textSize.Width > minSize.Width ? textSize.Width : minSize.Width;
                    textSize.Height = textSize.Height > minSize.Height ? textSize.Height : minSize.Height;
                }
            }
        }

        //create a new image of the right size
        Image retImg = new Bitmap((int)textSize.Width, (int)textSize.Height);
        using (var drawing = Graphics.FromImage(retImg)) {
            //Paint the background
            drawing.Clear(backColor);

            //create a brush for the text
            using (Brush textBrush = new SolidBrush(textColor)) {
                drawing.DrawString(currencyCode, font, textBrush, 0, 0);
                drawing.Save();
            }
        }
        return retImg;
    }

(imagemagick を使用して、画像上のテキストをレンダリングします(サーバー上)

C#を使用しているため、ビットマップとフォントの操作に.Netクラスを直接使用することもできます(次のようなクラスで:System.Drawing.BitmapおよびSystem.Drawing.Graphics

3
Toad

この answer に記載されているこのメソッドをVB.NETメソッドに変換しました。たぶんこれは誰かを助けます。

Public Function DrawText(ByVal text As String, ByRef font As   Font, ByRef textColor As Color, ByRef backColor As Color) As Image
    ' first, create a dummy bitmap just to get a graphics object
    Dim img As Image = New Bitmap(1, 1)
    Dim drawing As Graphics = Graphics.FromImage(img)

    ' measure the string to see how big the image needs to be
    Dim textSize As SizeF = drawing.MeasureString(Text, Font)

    ' free up the dummy image and old graphics object
    img.Dispose()
    drawing.Dispose()

    ' create a new image of the right size
    img = New Bitmap(CType(textSize.Width, Integer), CType(textSize.Height, Integer))

    drawing = Graphics.FromImage(img)

    ' Paint the background
    drawing.Clear(BackColor)

    ' create a brush for the text
    Dim textBrush As Brush = New SolidBrush(textColor)

    drawing.DrawString(text, font, textBrush, 0, 0)

    drawing.Save()

    textBrush.Dispose()
    drawing.Dispose()

    Return img

End Function

Edit:誤字を修正しました。

3
Freddy

これは、ライブラリクラスに追加するのに適した、オプションのパラメーターとドキュメントを含むKazarの回答のPanayiotis版です。

/// <summary>
/// Creates an image containing the given text.
/// NOTE: the image should be disposed after use.
/// </summary>
/// <param name="text">Text to draw</param>
/// <param name="fontOptional">Font to use, defaults to Control.DefaultFont</param>
/// <param name="textColorOptional">Text color, defaults to Black</param>
/// <param name="backColorOptional">Background color, defaults to white</param>
/// <param name="minSizeOptional">Minimum image size, defaults the size required to display the text</param>
/// <returns>The image containing the text, which should be disposed after use</returns>
public static Image DrawText(string text, Font fontOptional=null, Color? textColorOptional=null, Color? backColorOptional=null, Size? minSizeOptional=null)
{
    Font font = Control.DefaultFont;
    if (fontOptional != null)
        font = fontOptional;

    Color textColor = Color.Black;
    if (textColorOptional != null)
        textColor = (Color)textColorOptional;

    Color backColor = Color.White;
    if (backColorOptional != null)
        backColor = (Color)backColorOptional;

    Size minSize = Size.Empty;
    if (minSizeOptional != null)
        minSize = (Size)minSizeOptional;

    //first, create a dummy bitmap just to get a graphics object
    SizeF textSize;
    using (Image img = new Bitmap(1, 1))
    {
        using (Graphics drawing = Graphics.FromImage(img))
        {
            //measure the string to see how big the image needs to be
            textSize = drawing.MeasureString(text, font);
            if (!minSize.IsEmpty)
            {
                textSize.Width = textSize.Width > minSize.Width ? textSize.Width : minSize.Width;
                textSize.Height = textSize.Height > minSize.Height ? textSize.Height : minSize.Height;
            }
        }
    }

    //create a new image of the right size
    Image retImg = new Bitmap((int)textSize.Width, (int)textSize.Height);
    using (var drawing = Graphics.FromImage(retImg))
    {
        //Paint the background
        drawing.Clear(backColor);

        //create a brush for the text
        using (Brush textBrush = new SolidBrush(textColor))
        {
            drawing.DrawString(text, font, textBrush, 0, 0);
            drawing.Save();
        }
    }
    return retImg;
}
1
Andrew Taylor

F# バージョン:


open System.Drawing

let drawText text font textColor backColor =
    let size =
      use dummyImg = new Bitmap(1, 1)
      use drawing = Graphics.FromImage(dummyImg)
      drawing.MeasureString(text, font)
    let img = new Bitmap((int size.Width), (int size.Height))
    use drawing = Graphics.FromImage(img)
    use textBrush = new SolidBrush(textColor)
    do 
      drawing.Clear(backColor)
      drawing.DrawString(text, font, textBrush, PointF())
      drawing.Save() |> ignore
    img
1
Dzmitry Lahoda