Guide Programming

How to create image from url

How to convert any URL into an image with Node.js and the Pictify API, for thumbnails, social previews, and automated screenshot workflows.

Pictify Engineering Published 17 Oct 2024 3 min read

Introduction

In today's digital landscape, the ability to create images from URLs is an invaluable skill for web developers, content creators, and digital marketers. Whether you're building a web scraper, generating thumbnails, or creating social media previews, knowing how to convert a URL to an image can significantly enhance your projects. In this tutorial, we'll explore how to build a URL to Image converter using Node.js and the Pictify API.

Why Create Images from URLs?

  1. Thumbnail Generation: Create previews for web pages or articles.
  2. Social Media Sharing: Generate custom images for social media posts.
  3. Web Archiving: Capture visual snapshots of web pages for archival purposes.
  4. Content Monitoring: Track visual changes on websites over time.
  5. SEO Optimization: Create custom Open Graph images for better social sharing.

Prerequisites

Before we begin, make sure you have:

  1. Node.js installed on your machine
  2. A Pictify API key (sign up at pictify.io)
  3. Basic knowledge of JavaScript and Node.js

Install the required packages:

bash
npm install axios

Setting Up the Project

  1. Initialize a Node.js Project: Create a new directory for your project and initialize a Node.js project:
bash
mkdir url-to-image-converter
cd url-to-image-converter
npm init -y
  1. Install Dependencies: Install the axios library to make HTTP requests:
bash
npm install axios
  1. Create the Main Script: Create a new file named index.js and add the following code:
javascript
const axios = require('axios');
const fs = require('fs');
const path = require('path');

const API_KEY = 'YOUR_PICTIFY_API_KEY';

async function convertURLToImage(url) {
  try {
    const response = await axios.post('https://api.pictify.io/v1/image', {
      url,
      api_key: API_KEY
    });
    return response.data.image_url;
  } catch (error) {
    console.error('Error converting URL to image:', error);
    return null;
  }
}

async function main() {
  const url = 'https://example.com';
  const imageUrl = await convertURLToImage(url);
  if (imageUrl) {
    console.log('Image URL:', imageUrl);
  }
}

main();

Running the Script

Run the script using Node.js:

bash
node index.js

Creating a Image for a specific selector

  1. Follow the above steps to set up the project and install the dependencies.
  2. Update the script to include the selector:
javascript
const selector = '#elementId'; // Replace with your actual selector
  1. Add the selector to the request body:
javascript
const response = await axios.post('https://api.pictify.io/v1/image', {
  url,
  api_key: API_KEY,
  selector
});
  1. Run the script again:
bash
node index.js

Creating Image from url without code

We have a free online tool to create image from url without code here

  1. Go to pictify.io
  2. Click on the "Tools" tab
  3. Click on "URL to Image"
  4. Enter the URL of the website you want to create an image from
  5. Hover on the selector to highlight the element
  6. Click on the element to select it
  7. Click on "Create Image"
  8. The image will be created and you will be able to download it

Full-Page vs. Element-Targeted Capture

Not every screenshot needs the whole page. Pictify's selector parameter lets you capture a single element instead of the full rendered viewport, useful when you only care about one part of a page and don't want the rest of the layout (nav bars, footers, ads) in your output.

When to use full-page capture:

  • Competitor monitoring: you want to see the whole landing page, including how sections stack
  • Visual regression testing: comparing an entire page's layout across deploys
  • Archiving: a complete record of what a page looked like at a point in time

When to use element-targeted capture:

  • Pulling a pricing table out of a competitor's page for a comparison doc
  • Grabbing a single widget (a stock ticker, a status badge) to embed elsewhere
  • Generating a thumbnail from a specific <article> or <div> instead of the whole page, which usually looks cleaner than a shrunk full-page screenshot

Here's both in one script, so you can compare the output directly:

javascript
async function captureFullPage(url) {
  const response = await axios.post('https://api.pictify.io/v1/image', {
    url,
    api_key: API_KEY,
    full_page: true
  });
  return response.data.image_url;
}

async function captureElement(url, selector) {
  const response = await axios.post('https://api.pictify.io/v1/image', {
    url,
    api_key: API_KEY,
    selector
  });
  return response.data.image_url;
}

async function compareCaptures() {
  const url = 'https://example.com/pricing';
  const [fullPage, pricingTable] = await Promise.all([
    captureFullPage(url),
    captureElement(url, '.pricing-table')
  ]);
  console.log('Full page:', fullPage);
  console.log('Pricing table only:', pricingTable);
}

If your selector doesn't match anything on the page, Pictify falls back to a full-page capture rather than failing outright (worth knowing if you're running this against pages you don't fully control).

Handling Slow-Loading or JS-Heavy Pages

A plain "load the URL and screenshot it" approach breaks down fast on modern sites. Client-side rendered dashboards, lazy-loaded images, and CSS animations can all mean the page you screenshot isn't the page a human would actually see: you'll capture a loading spinner or a half-rendered layout instead of real content.

Two ways to handle this:

Wait for a specific selector. If you know which element signals "the page is actually ready" (a chart finishing render, a data table populating), wait for it directly instead of guessing at a timeout:

javascript
async function captureWithWait(url) {
  const response = await axios.post('https://api.pictify.io/v1/image', {
    url,
    api_key: API_KEY,
    wait_for_selector: '.dashboard-loaded',
    delay: 2000 // fallback if the selector never appears, in ms
  });
  return response.data.image_url;
}

Use a fixed delay. Simpler, but less reliable: good for pages where you don't have a clean "ready" signal but know roughly how long rendering takes:

javascript
async function captureWithDelay(url, delayMs = 3000) {
  const response = await axios.post('https://api.pictify.io/v1/image', {
    url,
    api_key: API_KEY,
    delay: delayMs
  });
  return response.data.image_url;
}

Prefer wait_for_selector when you can; it captures as soon as the page is actually ready instead of always eating the full delay, which matters if you're doing this at any volume.

Caching and Avoiding Redundant Renders

If you're screenshotting the same URL repeatedly (a dashboard on a cron job, a status page checked every few minutes), re-rendering on every request wastes render credits and adds latency for no reason. A simple cache keyed on the URL and request options avoids that:

javascript
const crypto = require('crypto');

// Swap this Map for Redis or another shared cache in production;
// an in-memory Map only helps within a single process.
const cache = new Map();
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes

function cacheKey(url, options = {}) {
  return crypto.createHash('sha256').update(url + JSON.stringify(options)).digest('hex');
}

async function convertURLToImageCached(url, options = {}) {
  const key = cacheKey(url, options);
  const cached = cache.get(key);

  if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
    return cached.imageUrl;
  }

  const response = await axios.post('https://api.pictify.io/v1/image', {
    url,
    api_key: API_KEY,
    ...options
  });

  const imageUrl = response.data.image_url;
  cache.set(key, { imageUrl, timestamp: Date.now() });
  return imageUrl;
}

Set CACHE_TTL_MS based on how often the underlying page actually changes: a status dashboard might need a 30-second TTL, while a mostly-static landing page could go hours between re-renders.

Conclusion

In this tutorial, we've learned how to create images from URLs using Node.js and the Pictify API. This powerful tool can be used for a variety of applications, from generating thumbnails to capturing visual snapshots of web pages. By leveraging the capabilities of modern web technologies and APIs, you can enhance your projects with dynamic and engaging visual content.

We hope you found this tutorial helpful and that you'll explore the possibilities of URL to Image conversion in your own projects. Happy coding!

Ship documents, images and video from one template.

50 renders a month on the free tier. No card, no watermark.

Start free