Read more

Generating test images on the fly via JavaScript or Ruby

Arne Hartherz
March 23, 2018Software engineer at makandra GmbH

When you need test images, instead of using services like lorempixel Show archive.org snapshot or placehold.it Show archive.org snapshot you may generate test images yourself.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Here we build a simple SVG image and wrap it into a data: URI. All browsers support SVG, and you can easily adjust it yourself.
Simply set it as an image's src attribute.

JavaScript

Simple solution in modern JavaScript, e.g. for use in the client's browser:

function svgUri(text) {
  let svg = `
    <svg width="320" height="240" xmlns="http://www.w3.org/2000/svg">
      <rect x="0" y="0" width="320" height="240" style="fill: #ddd; stroke: #666; stroke-width: 4;" />
      <text x="50%" y="50%" font-size="24" text-anchor="middle" alignment-baseline="middle" fill="#666">
        ${text}
      </text>
    </svg>
  `
  return 'data:image/svg+xml;charset=utf8,' + window.escape(svg)
}

See the attached JSFiddle for an example.

Ruby

If you like to do it on the server, here is some Ruby for you:

def svg_uri(text)
  svg = <<~SVG
    <svg width="480" height="270" xmlns="http://www.w3.org/2000/svg">
      <rect x="0" y="0" width="480" height="270" style="fill: #ddd; stroke: #666; stroke-width: 4;" />
      <text x="50%" y="50%" font-size="24" text-anchor="middle" alignment-baseline="middle" fill="#666">
        #{text}
      </text>
    </svg>
  SVG

  "data:image/svg+xml;charset=utf8,#{ERB::Util.url_encode(svg)}"
end
Posted by Arne Hartherz to makandra dev (2018-03-23 10:49)