Let’s use the fetch API to resize an image in node. We’ll load the image from disk before sending it. We’ll also change the JPEG quality to get the size down.
We’re doing this on the server side in node using the node-fetch
library.
If you just want the script jump to the bottom of the page.
First let’s require
the libraries we’re going to use.
const fetch = require("node-fetch");
const FormData = require('form-data');
const fs = require("fs");
Now we’ll read the file from disk and use the form-data
library to package it up to send.
const frm = new FormData();
const filename = 'test-input-image.png';
const buffer = fs.readFileSync("res/" + filename);
frm.append('image', buffer, {
contentType: 'application/octet-stream',
name: 'image',
filename: filename,
});
We add an args
variable to tell the API what we want to do with the image. In this case we want the API to resize it to 300 pixels and lower the JPEG image quality to 75%.
frm.append("args", "-resize 300 -quality 75");
Finally, we set some headers and POST the result to the API.
We’re using the filename output.jpg
to specify the name and format of the resulting image. If you change the file extension it will change the format of the resulting file. For example if you wanted to save as a PNG file change output.jpg
to output.png
in the url
.
Once we get the result back we use fs.writeFileSync
to write the resulting image into a file called output.jpg
.
const url = 'https://magic-image.p.rapidapi.com/convert-cli/output.jpg';
const headers = frm.getHeaders();
headers['x-rapidapi-key'] = process.env["RAPIDAPI_KEY"];
headers['x-rapidapi-host'] = 'magic-image.p.rapidapi.com'
fetch(url, {method: 'POST', body: frm, headers: headers})
.then(res => res.blob())
.then(blob => blob.arrayBuffer())
.then(buffer => fs.writeFileSync("output.jpg", Buffer.from(buffer)));
And that’s it. Here’s what we did:
test-input-image.png
from disk.FormData
.output.jpg
.const fetch = require("node-fetch");
const FormData = require('form-data');
const fs = require("fs");
const frm = new FormData();
const filename = 'test-input-image.png';
const buffer = fs.readFileSync("res/" + filename);
frm.append('image', buffer, {
contentType: 'application/octet-stream',
name: 'image',
filename: filename,
});
frm.append("args", "-resize 300 -quality 75");
const url = 'https://magic-image.p.rapidapi.com/convert-cli/output.jpg';
const headers = frm.getHeaders();
headers['x-rapidapi-key'] = process.env["RAPIDAPI_KEY"];
headers['x-rapidapi-host'] = 'magic-image.p.rapidapi.com'
fetch(url, {method: 'POST', body: frm, headers: headers})
.then(res => res.blob())
.then(blob => blob.arrayBuffer())
.then(buffer => fs.writeFileSync("output.jpg", Buffer.from(buffer)));