How to Convert an Image to JPG/JPEG Format using JavaScript

Cloudmersive
2 min readAug 9, 2022

--

In spite of many other image formats gaining popularity over the years, JPG remains the most ubiquitous image format around. If you’re looking for a quick way to convert photos to JPG on your website, you aren’t alone — and that’s why our JPG conversion API exists. With this API, you can easily convert dozens of common image formats to JPG automatically through a simple cloud service. It’s free to use — just register a free account on our website and you’ll receive an API key which can be used to authenticate this & dozens of other similar APIs. Below, I’ve included ready-to-run code snippets to help you structure your API call in JavaScript.

We’ll cover two different methods to call this API. The first involves using the built-in XHR feature. Use the below code examples:

var data = new FormData();
data.append("imageFile", fileInput.files[0], "file");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.cloudmersive.com/image/convert/to/jpg/%3Cinteger%3E");xhr.setRequestHeader("Apikey", "YOUR-API-KEY-HERE");xhr.send(data);

The second method starts with jQuery libary installation by running the below command:

bower install jquery

After that, call the API with the below code:

var form = new FormData();
form.append("imageFile", fileInput.files[0], "file");
var settings = {
"url": "https://api.cloudmersive.com/image/convert/to/jpg/<integer>",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "multipart/form-data",
"Apikey": "YOUR-API-KEY-HERE"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});

Just like that, you’re all done. No more coding required!

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.