Features

August 5, 2022

URL to Image

Convert a URL into an Image in the favourite format for taking screenshots of websites.

Jonathan Markwell
Jonathan Markwell
6 min read
Share this article:

Turning a URL into an Image is one of the most common jobs developers use Urlbox for.

Urlbox is powerful with dozens of features for taking screenshots at scale. The most basic request is as simple as forming a URL like the following:

https://api.urlbox.io/v1/[API_KEY]/png?url=example.com

Yes you can literally create an HTML image tag and it will render:

<img src="https://api.urlbox.io/v1/[API_KEY]/png?url=example.com" />

Like this:

Example HTML rendered as a PNG

However, you'll notice your API key is embedded in that URL. Anyone could potentially start using your API key to make requests against the Urlbox API - and use up your quota. So, if your Urlbox URLs are used publicly, you should prevent anonymous usage with an authenticated request format. See how to do that in our docs.

If want to generate your image tags for turning URLs into Images with code we've included examples of how you can do it in different languages below.

URL to Image in Node.js

// npm install urlbox --save
 
import Urlbox from "urlbox";
 
// Plugin your API key and secret
const urlbox = Urlbox(YOUR_API_KEY, YOUR_API_SECRET);
 
// Set your options
const options = {
  url: "example.com",
  format: "png",
};
 
const imgUrl = urlbox.generateRenderLink(options);
// https://api.urlbox.io/v1/YOUR_API_KEY/TOKEN/png?url=example.com
 
// Now set it as the src in an img tag to render the screenshot
<img src={imgUrl} />;

URL to Image in Ruby

# ruby gem coming soon
require 'openssl'
require 'open-uri'
 
def encodeURIComponent(val)
  URI.escape(val, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
end
 
def urlbox(url, options={}, format='png')
  urlbox_apikey = 'YOUR_API_KEY'
  urlbox_secret = 'YOUR_API_SECRET'
 
  query = {
    url: url
  }
 
  query_string = query.
    sort_by {|s| s[0].to_s }.
    select {|s| s[1] }.
    map {|s| s.map {|v| encodeURIComponent(v.to_s) }.join('=') }.
    join('&')
 
  token = OpenSSL::HMAC.hexdigest('sha256', urlbox_secret, query_string)
 
  "https://api.urlbox.io/v1/#{urlbox_apikey}/#{token}/#{format}?#{query_string}"
end
 
url = urlbox("example.com", {}, 'png')
puts url
# url: "https://api.urlbox.io/v1/YOUR_API_KEY/TOKEN/png?url=www.google.com"

URL to Image in PHP

// run this on the command line to install the urlbox php package:
// composer require urlbox/screenshots
 
use Urlbox\Screenshots\Urlbox;
 
$urlbox = Urlbox::fromCredentials('API_KEY', 'API_SECRET');
 
// only required option is a url:
$options['url'] = 'example.com';
 
// specify any other options to augment the screenshot...
$options['width'] = 320;
 
// Create the Urlbox URL
$urlboxUrl = $urlbox->generateSignedUrl($options);
 
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com&width=320'
 
// Generate a screenshot by loading the Urlbox URL in an img tag:
echo '<img src="'.$urlboxUrl.'" alt="Test screenshot generated by Urlbox">'

URL to Image in Python

# PyPi package coming soon!
#!/usr/bin/python
 
import hmac
from hashlib import sha256
 
try:
  from urllib import urlencode
except ImportError:
  from urllib.parse import urlencode
 
def urlbox(args):
  apiKey = "xxx-xxx"
  apiSecret = "xxx-xxx"
  queryString = urlencode(args, True)
  hmacToken = hmac.new(str.encode(apiSecret), str.encode(queryString), sha256)
  token = hmacToken.hexdigest().rstrip('\n')
  return "https://api.urlbox.io/v1/%s/%s/png?%s" % (apiKey, token, queryString)
 
argsDict = {'url' : "twitter.com", 'thumb_width': 400}
print(urlbox (argsDict))

URL to Image in Java

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.HashMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
 
public class Urlbox {
 
  private String key;
  private String secret;
 
  Urlbox(String api_key, String api_secret) {
    this.key = api_key;
    this.secret = api_secret;
  }
 
  // main method demos Example Usage
  public static void main(String[] args) {
    String urlboxKey = "your-urlbox-api-key";
    String urlboxSecret = "your-urlbox-secret";
 
    // Set request options
    Map<String, Object> options = new HashMap<String, Object>();
    options.put("width", 1280);
    options.put("height", 1024);
    options.put("thumb_width", 240);
    options.put("full_page", "false");
    options.put("force", "false");
 
    // Create urlbox object with api key and secret
    Urlbox urlbox = new Urlbox(urlboxKey, urlboxSecret);
    try {
      // Call generateUrl function of urlbox object
      String urlboxUrl = urlbox.generateUrl("bbc.co.uk", options);
      // Now do something with urlboxUrl.. put in img tag, etc..
    } catch (UnsupportedEncodingException ex) {
      throw new RuntimeException("Problem with url encoding", ex);
    }
  }
 
  public String generateUrl(String url, Map<String,Object> options) throws UnsupportedEncodingException {
 
    String encodedUrl = URLEncoder.encode(url, "UTF-8");
    String queryString = String.format("url=%s", encodedUrl);
 
    for (Map.Entry<String, Object> entry : options.entrySet()) {
      String queryParam = "&"+entry.getKey()+"="+entry.getValue();
      queryString += queryParam;
    }
 
    String token = generateToken(queryString, this.secret);
    String result = String.format("https://api.urlbox.io/v1/%s/%s/png?%s", this.key, token, queryString);
    System.out.println(result);
    return result;
  }
 
  private String generateToken(String input, String key) {
    String lSignature = "None";
    try {
      final Mac lMac = Mac.getInstance("HmacSHA256")
      final SecretKeySpec lSecret = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA256")
      lMac.init(lSecret)
      final byte[] lDigest = lMac.doFinal(input.getBytes())
      final StringBuilder lSignature = new StringBuilder();
      for (byte b : lDigest) {
        lSignature.append(String.format("%02x", b));
      }
      return lSignature.toString().toLowerCase()
    } catch (NoSuchAlgorithmException lEx) {
      throw new RuntimeException("Problems calculating HMAC", lEx)
    } catch (InvalidKeyException lEx) {
      throw new RuntimeException("Problems calculating HMAC", lEx)
    }
    return lSignature;
  }
}

URL to Image in C#

 
using UrlboxMain;
 
namespace Screenshot
{
  public class Screenshotter
  {
    Urlbox urlbox = new Urlbox("YOUR_URLBOX_API_KEY", "YOUR_URLBOX_API_SECRET");
 
    public void GetScreenshotUrl()
    {
      dynamic options = new ExpandoObject();
      options.Width = 1280;
      options.Thumb_Width = 500;
      options.Full_Page = true;
 
      var output = urlbox.GenerateUrl("bbc.co.uk", options);
      // output is now https://api.urlbox.io/v1/YOUR_URLBOX_API_KEY/d6b5068716c19ba4556648ad9df047d5847cda0c/png?url=bbc.co.uk&width=1280&thumb_width=500&full_page=true
      // to generate a screenshot image you would make a simple GET request to this URL, for example putting it inside an <img> tag.
    }
  }
}
 // ================================================================
// UrlboxMain project/package:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using PCLCrypto;
 
namespace UrlboxMain
{
  public class Urlbox
  {
    String apiKey;
    String apiSecret;
    static List<String> encodedPropertyNames = new List<String> { "user_agent", "bg_color", "hide_selector", "click_selector", "highlight", "highlightbg", "highlightfg" };
    static List<String> booleanPropertyNames = new List<String> { "force", "retina", "full_page", "disable_js" };
 
    public Urlbox(String apiKey, String apiSecret)
    {
      if (String.IsNullOrEmpty(apiKey) || String.IsNullOrEmpty(apiSecret))
      {
        throw new ArgumentException("Please provide your Urlbox.io API Key and API Secret");
      }
      this.apiKey = apiKey;
      this.apiSecret = apiSecret;
    }
 
    public string GenerateUrl(string url)
    {
      return this.GenerateUrl(url, new ExpandoObject());
    }
 
    public string GenerateUrl(string url, ExpandoObject options)
    {
      if (String.IsNullOrEmpty(url))
      {
        throw new ArgumentException("Please provide a url in order to generate a screenshot URL");
      }
      var encodedUrl = urlEncode(url);
      var format = "png";
 
      byte[] key = Encoding.UTF8.GetBytes(this.apiSecret);
      var urlString = string.Format("url={0}", encodedUrl);
      StringBuilder sb = new StringBuilder(urlString);
 
      foreach (KeyValuePair<string, object> kvp in options)
      {
        var optionName = kvp.Key.ToLower();
        var optionValue = kvp.Value.ToString();
        if (String.IsNullOrEmpty(optionValue))
        {
          continue;
        }
        if (string.Equals(optionName, "format")){
          format = optionValue;
          continue;
        }
        if (encodedPropertyNames.Contains(optionName))
        {
          optionValue = urlEncode(optionValue);
        }
        if (booleanPropertyNames.Contains(optionName))
        {
          if (!(bool)kvp.Value) { continue; }
          optionValue = optionValue.ToLower();
        }
        sb.Append(string.Format("&{0}={1}", optionName, optionValue));
      }
 
      var queryString = sb.ToString();
      var uniqueToken = generateToken(queryString, key);
      return string.Format("https://api.urlbox.io/v1/{0}/{1}/{2}?{3}", this.apiKey, uniqueToken, format, queryString);
    }
 
    private static string generateToken(String data, byte[] key)
    {
      var algorithm = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha256);
      CryptographicHash hasher = algorithm.CreateHash(key);
      hasher.Append(Encoding.UTF8.GetBytes(data));
      byte[] mac = hasher.GetValueAndReset();
      var macStr = byteArrayToString(mac);
      return macStr;
    }
 
    private static string byteArrayToString(byte[] ba)
    {
      string hex = BitConverter.ToString(ba).ToLower();
      return hex.Replace("-", "");
    }
 
    private static string urlEncode(string url)
    {
      // make it behave like javascript encodeURIComponent()
      var encoded = Uri.EscapeDataString(url);
      encoded = encoded.Replace("%28", "(");
      encoded = encoded.Replace("%29", ")");
      return encoded;
    }
 
  }
}
 

You're not limited to PNG

Urlbox has many image formats beyond PNG. You can also render:

  • PDF
  • JPEG
  • WebP
  • SVG
  • AVIF
  • HTML (after JS has executed)
  • JSON (Coming soon).

More Urlbox Features

If you found this useful you might also want to checkout some of our other popular Urlbox features:

Index

All Features

Free Trial

Designers, law firms and infrastructure engineers trust Urlbox to accurately and securely convert HTML to images at scale. Experience it for yourself.