2010-01-15 18 views
47

¿Alguien puede guiar cómo generar imágenes desde el texto de entrada. La imagen puede tener cualquier extensión no importa.Cómo generar una imagen desde el texto en vuelo en tiempo de ejecución

+0

¿Quieres decir una imagen como se obtendría a partir de una captura de pantalla? Ciertamente, * algunos * formatos/extensiones serían mejores que otros. – pavium

+0

¿A qué tipo de entrada de texto se refiere? –

+0

No, no es captura de pantalla, tenemos cuadro de texto de entrada y estamos usando C# – Ravia

Respuesta

123

Ok, suponiendo que desea dibujar una cadena en una imagen en C#, que se va a necesitar utilizar el espacio de nombres System.Drawing aquí:

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; 

} 

Este código medirá la primera cadena, una y luego crea una imagen del tamaño correcto.

Si desea guardar la devolución de esta función, simplemente llame al método Guardar de la imagen devuelta.

+6

La línea "Imagen img = nuevo mapa de bits (0, 0);", no funciona: no puede crear una imagen de 0 tamaño. Cambiarlo a "nuevo mapa de bits (1, 1)", funciona. – neminem

+3

Si agrega 'drawing.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;' antes de la línea 'drawing.DrawString (text, font, textBrush, 0, 0);', obtendrá un texto suavizado anti-alias . – LoneBunny

3

uso imagemagick para la representación de texto en imágenes (en el servidor)

Ya que estás en C# También puede utilizar las clases de .NET para mapa de bits y la fuente de manipulación directa (con las clases como: System.Drawing.Bitmap y System.Drawing.Graphics)

3

Acabo de traducir este método mencionado en este answer a un método VB.NET. Tal vez esto ayude a alguien.

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 

Editar: error tipográfico fijo.

+0

Gracias Freddy, me has ahorrado mucha energía. – BedfordNYGuy

1

F# versión:


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 
3

Gracias Kazar. Una ligera mejora de la respuesta anterior a utilizar para la USO disponer de los objetos de imágenes/gráficos después de su uso y la introducción del parámetro min tamaño

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; 
    } 
Cuestiones relacionadas