How to Generate an Image from Text on Fly at Runtime

How to generate an image from text on fly at runtime

Ok, assuming you want to draw a string on an image in C#, you are going to need to use the System.Drawing namespace here:

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;

}

This code will measure the string first, and then create an image of the correct size.

If you want to save the return of this function, just call the Save method of the returned image.

Saving text to image in server

Here are some things you can do:

  • Make sure the folder where you are writing to foresees modify rights to the IIS Apppool identity of the application. You'll need to add it by searching for it in full instead of just the identity, so

IIS APPPOOL\YourAppsIdentity

(note the space between IIS and APPPOOL) and be sure to set the search location to the server machine, not to the domain, which is what it would default to if the machine is joined into one (otherwise the name won't resolve).

  • In your application's Web.config file you could also set <customErrors mode="Off"> (in the <system.web> section) during development so you get some more verbose error descriptions in the browser window if or when exceptions do bubble up. They can help you on your way to figure out what's going wrong. Don't forget to remove the entry from the Web.config file again once the application goes into production or set the value to "On" if you do, in fact, use custom errors.
  • You can make this code a little more robust by doing some access control checks on the directory before attempting a write operation. this can help you on your way.

Hope this helps.

iTextSharp 5: Create image from text

Apparently, there is no iTextSharp way of doing this.

This approach worked for me How to generate an image from text on fly at runtime

That way I didn't have to include any 3rd party libraries.

create image from text(email) to prevent spammers use

Check this answer, it should help guide you in the right direction. It draws text on an image.

https://stackoverflow.com/a/2070493/907388

This article also is a great example to generate an image from text or convert text into image

http://chiragrdarji.wordpress.com/2008/05/09/generate-image-from-text-using-c-or-convert-text-in-to-image-using-c/

You can also generate images from text server side with imageMagick

EDIT:

The methods above assume you will save the image. The following method below will encode the image object to Base64 string so you do not have to save the image directly.

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format) 
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();

// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}

After encoding the image, use the base64String return value from ImageToBase64 in an img as such:

<img src="data:image/png;base64, iAAANSUhEQAA..." alt="my encoded image"/>

Just replace iAAANSUhEQAA... with the actual value, which could be quite large depending on the size of the image.

And one more note, data-uri do not work in IE6/7

credit: http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx

How to generate an image from dynamically created HTML in Nodejs?

A little bit of a self-plug here but I just recently did the same thing with a project called kb-hologram.

It basically takes handlebar templates (either SVG or HTML), and renders that to either an SVG or png.

Basically, after having a ready HTML file, I load the HTML into a puppeteer instance (which actually runs a headless chrome browser), take a snapshot of the rendered HTML, and saves it.

it can generate things like a test report image (obviously fake numbers), or a changelog image similar to what vscode publishes in their tweets:
Sample Image

HTML

Here's the gist of it:

// handles rendering the HTML templates
// https://github.com/puppeteer/puppeteer
import puppeteer from 'puppeteer';
import { writeFile } from 'fs-extra';

(async () => {

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({
height: this.options.height,
width: this.options.width
});

// If your HTML is saved to a file, you load it like this:
await page.goto('file://' + this.templateFilePath);

// if your HTML is in memory (as a string), you load it like this:
// page.setContent(htmlString);

const imageBuffer = await page.screenshot({});

await browser.close();

// write file to disk as buffer
await writeFile('rendered.png', imageBuffer);

// convert to base64 string if you want to:
console.log(imageBuffer.toString('base64'));
})();

SVG

Generating an SVG is much simpler since it's basically a text file:

import { compile } from 'handlebars';

(async (data) => {
// generate the svg template as string
const template = await this.getTemplateAsString();

// make it a handlebars template
const handlebarsTemplate = compile(template);

// load the data into the template
// this is basically the content of the SVG file
const svgString = handlebarsTemplate(data);

// from here on, it's basically the same thing :-)
const svgBuffer = Buffer.from(svgString, 'utf8');
})(data);

Headless browser

To me, handling things like external resources is easier on a real browser if you want to load fonts and styles from CDNs.
There are solutions out there to take a screenshot from jsdom directly if you don't want to introduce another "browser" module into the mix.
Also, take note that this will download an instance of chrome as a dependency


kb-hologram

The project is still in early stages. Feel free to contribute to kb-hologram, fork the code, or write your own using the example. I personally use it on Travis CI to publish tweets and images as PR comments on GitHub.

How to generate an image from a snippet of HTML code (as it is interpreted by the browser) on fly at runtime

See: rendering html to png (server-side)

And as you want a Java API, Html2Image is the best solution for you.

Simple way to create an image file with drawing commands in console program

Using the System.Drawing.Bitmap class and it's entourage, you could do it very simply like:

static void Main(string[] args) {

int width = 512;
int height = 512;

int x, y, w, h;
x = y = 10;
w = h = 100;

using (Bitmap bmp = new Bitmap(width, height)) {
using (Graphics g = Graphics.FromImage(bmp)) {

g.FillRectangle(
brush: new SolidBrush(
color: Color.Blue
),
rect: new Rectangle(x, y, w, h)
);

g.DrawRectangle(
pen: new Pen(
color: Color.Black,
width: 3
),
rect: new Rectangle(x, y, w, h)
);

bmp.Save(@"D:\result.png", ImageFormat.Png);

}
}

}

You will need to reference the System.Drawing assembly and also add the
following using clauses:

using System.Drawing;
using System.Drawing.Imaging;


Related Topics



Leave a reply



Submit