0

I own a few fanpages on facebook in which I post images containing funny text ( like the example below ). Across all the pages I use the same text but with different background images. The sizes of the background is always the same. Only the color changes. Since I have to save each picture with a different background individually, I am now trying to create a small script that allows me to store the creates text with different backgrounds as a jpg or png file. Here is how i imagine the process:

  1. I would add text to a textarea which would be a part of a normal html form.

  2. With javascript I would like to fit the text ( in fontsize, width and height ) within the white border of the sample below.

  3. When the form gets submited the script should then run through a loop and save the text on each different background in a seperate folder.

Here is an example of what the output should look like

enter image description here

There are parts of my plan that i know how to figure out. But there are two things I am stuck with.

  1. How can i adjust the text so that it fits within the white border of the sample image?

  2. How can i create an image out of a background image and some text on top of that.

Does anybody have an idea on how to approach this? Or maybe even a fully working script I could use for that?

miken32
  • 42,008
  • 16
  • 111
  • 154
Dennis
  • 595
  • 1
  • 6
  • 22

1 Answers1

0

I'm not sure there's a way to do this kind of image generation in PHP. You tagged it Javascript so I assume you have a front-end.

I was about to suggest something like FitText.js but in order to save your work as an image file, you'd need to use the Canvas API. It has a toDataUrl('image/jpeg') method.

You can use canvasCtx.drawImage to create the image background. A canvasCtx.strokeRect to create a rectangle that has a border. And canvasCtx.fillText to draw the text.

Fit text to a container

There's a method in the canvas to measure how much space the text will take up at its current font size. However, this won't wrap the text when there's available vertical space, putting it all on one line instead. A better solution would be to have a fixed font size and multiple lines in a <textarea> or multiple <input>s, allowing you to fit the text as discussed in the following stack overflow thread:

Size to fit font on a canvas

Save the image to a file

Check out this thread: Save canvas as jpg to desktop

Honestly, after all of that, I'd say it would be easier to set up a little bit of automation in whatever photo editor you use. For example, a template PSD in Photoshop.

Community
  • 1
  • 1
Dan Bovey
  • 195
  • 2
  • 11