Generate image using JavaScript
Here's a simple example to show you how to generate an image using JavaScript. We'll use a JSON payload to define the image's dimensions, style, and content, including text and an embedded image.
JSON Payload
The JSON payload defines the image's dimensions, background color, and an array of blocks. Each block can be either text or an image, with properties such as position, size, and styling.
Here's the JSON structure we'll use:
1const data = { 2 "width": 1024, 3 "height": 1024, 4 "imageStyle": { "backgroundColor": "#d13d3d" }, 5 "blocks": [ 6 { 7 "id": "text-1", 8 "type": "text", 9 "x": 195, 10 "y": 145, 11 "fontSize": "80px", 12 "fontStyle": "normal", 13 "fontColor": "red", 14 "text": "Lorem Ipsum", 15 "textAlign": "left", 16 "width": 650, 17 "height": 131, 18 "backgroundColor": "#ffffff", 19 "borderRadius": "25px", 20 "border": "10px solid #000000" 21 }, 22 { 23 "id": "image-2", 24 "type": "image", 25 "x": 315, 26 "y": 372, 27 "image": "https://eoimages.gsfc.nasa.gov/images/imagerecords/153000/153502/michiganfall_vir2_20241019_th.jpg", 28 "width": 413, 29 "height": 405, 30 "borderRadius": "25px", 31 "border": "10px solid #000000" 32 } 33 ] 34};
Checkout the API contract for Image template defined in the API reference for more details on how to format the images.
Fetch Command and Save Image
To generate the image, we'll use a simple fetch command with a POST request. This command sends our JSON payload to the API, which then returns the generated image. We can save this image to a file for further use.
1// Fetch Command 2 3const apiKey = 'YOUR_API_KEY' 4const url = 'https://pixiegenie.saasysoup.com/api/v1/image.png' 5 6fetch(url, { 7 method: 'POST', 8 headers: { 9 'Content-Type': 'application/json', 10 Authorization: `Bearer ${apiKey}` 11 }, 12 body: JSON.stringify(data) 13}) 14 .then((response) => response.body.getReader().read()) 15 .then((buffer) => { 16 const fs = require('fs') 17 fs.writeFileSync('image.png', Buffer.from(buffer.value)) 18 console.log('Image saved as image.png') 19 }) 20 .catch((error) => console.error('Error:', error)) 21 22// Save this script in a file named generateImage.js
Run to following command to generate the image
1node generateImage.js