The simplest way is to use a canvas element and then invoke a download action allowing the user to select where to save the image.

You mention that the image is large, but not how much - be aware that with canvas you will also run into restrictions when the image source starts to touch around the 8k area in pixel size.

A simplified example (IE will require a polyfill for toBlob()).:

  • Load image source via input
  • Use File blob directly as image source via URL.createObjectURL()
  • When loaded, create a temporary canvas, set canvas size = image size and draw in image
  • Use toBlob() (more efficient on memory and performance and require no transcoding to/from Base64) to obtain a Blob.
  • We'll convert the Blob to File (a subset object and it will reference the same memory) so we can also give a filename as well as (important!) a binary mime-type.

Since the mime-type for the final step is binary the browser will invoke a Save as dialog.

document.querySelector("input").onchange = function() {
  var img = new Image;
  img.onload = convert;
  img.src = URL.createObjectURL(this.files[0]);
};

function convert() {
  URL.revokeObjectURL(this.src);             // free up memory
  var c = document.createElement("canvas"),  // create a temp. canvas
      ctx = c.getContext("2d");
  c.width = this.width;                      // set size = image, draw
  c.height = this.height;
  ctx.drawImage(this, 0, 0);
  
  // convert to File object, NOTE: we're using binary mime-type for the final Blob/File
  c.toBlob(function(blob) {
    var file = new File([blob], "MyJPEG.jpg", {type: "application/octet-stream"});
    window.location = URL.createObjectURL(file);
  }, "image/jpeg", 0.75);  // mime=JPEG, quality=0.75
}

// NOTE: toBlob() is not supported in IE, use a polyfill for IE.
<label>Select image to convert: <input type=file></label>

Update: If you just are after a string (base-64 encoded) version of the newly created JPEG simply use toDataURL() instead of toBlob():

document.querySelector("input").onchange = function() {
  var img = new Image;
  img.onload = convert;
  img.src = URL.createObjectURL(this.files[0]);
};

function convert() {
  URL.revokeObjectURL(this.src);             // free up memory
  var c = document.createElement("canvas"),  // create a temp. canvas
      ctx = c.getContext("2d");
  c.width = this.width;                      // set size = image, draw
  c.height = this.height;
  ctx.drawImage(this, 0, 0);
  
  // convert to File object, NOTE: we're using binary mime-type for the final Blob/File
  var jpeg = c.toDataURL("image/jpeg", 0.75);  // mime=JPEG, quality=0.75
  console.log(jpeg.length)
}
<label>Select image to convert: <input type=file></label>

Answer from user1693593 on Stack Overflow
Top answer
1 of 2
13

The simplest way is to use a canvas element and then invoke a download action allowing the user to select where to save the image.

You mention that the image is large, but not how much - be aware that with canvas you will also run into restrictions when the image source starts to touch around the 8k area in pixel size.

A simplified example (IE will require a polyfill for toBlob()).:

  • Load image source via input
  • Use File blob directly as image source via URL.createObjectURL()
  • When loaded, create a temporary canvas, set canvas size = image size and draw in image
  • Use toBlob() (more efficient on memory and performance and require no transcoding to/from Base64) to obtain a Blob.
  • We'll convert the Blob to File (a subset object and it will reference the same memory) so we can also give a filename as well as (important!) a binary mime-type.

Since the mime-type for the final step is binary the browser will invoke a Save as dialog.

document.querySelector("input").onchange = function() {
  var img = new Image;
  img.onload = convert;
  img.src = URL.createObjectURL(this.files[0]);
};

function convert() {
  URL.revokeObjectURL(this.src);             // free up memory
  var c = document.createElement("canvas"),  // create a temp. canvas
      ctx = c.getContext("2d");
  c.width = this.width;                      // set size = image, draw
  c.height = this.height;
  ctx.drawImage(this, 0, 0);
  
  // convert to File object, NOTE: we're using binary mime-type for the final Blob/File
  c.toBlob(function(blob) {
    var file = new File([blob], "MyJPEG.jpg", {type: "application/octet-stream"});
    window.location = URL.createObjectURL(file);
  }, "image/jpeg", 0.75);  // mime=JPEG, quality=0.75
}

// NOTE: toBlob() is not supported in IE, use a polyfill for IE.
<label>Select image to convert: <input type=file></label>

Update: If you just are after a string (base-64 encoded) version of the newly created JPEG simply use toDataURL() instead of toBlob():

document.querySelector("input").onchange = function() {
  var img = new Image;
  img.onload = convert;
  img.src = URL.createObjectURL(this.files[0]);
};

function convert() {
  URL.revokeObjectURL(this.src);             // free up memory
  var c = document.createElement("canvas"),  // create a temp. canvas
      ctx = c.getContext("2d");
  c.width = this.width;                      // set size = image, draw
  c.height = this.height;
  ctx.drawImage(this, 0, 0);
  
  // convert to File object, NOTE: we're using binary mime-type for the final Blob/File
  var jpeg = c.toDataURL("image/jpeg", 0.75);  // mime=JPEG, quality=0.75
  console.log(jpeg.length)
}
<label>Select image to convert: <input type=file></label>

2 of 2
0

JavaScript on the client side can not save files. You have multiple options:

  1. Render the image on an <canvas> element. This way it can be saved with right click -> save image
  2. Inset the image as <img> element. This way it can be saved with right click -> save image
  3. Send the image data as base64 string to the server. Do the processing there
  4. Use a server side language like PHP or Node.js to save the file

Long story short, you have to use some server side logic to save the file on disk

🌐
Medium
cloudmersive.medium.com › how-to-convert-an-image-to-jpg-jpeg-format-using-javascript-f703b8a88e18
How to Convert an Image to JPG/JPEG Format using JavaScript | by Cloudmersive | Medium
August 9, 2022 - 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/<integer>");xhr.setRequestHeader("Apikey", "YOUR-API-KEY-HERE");xhr.send(data);
🌐
ConvertAPI
convertapi.com › jpg-to-jpg › javascript
JPG to JPG Conversion JavaScript SDK – Optimize JPEG files efficiently
Re‑encode JPG, JPEG, and JFIF via JavaScript library. Control color space, JPEG quality, resolution, scaling, and size to balance clarity and file size.
People also ask

How to convert several image into JPG?
Open the site: image into JPG. Drag and drop image files to quickly convert them into JPG. Or just use a code sample in JavaScript with a few lines of code.
  1. Install Aspose.Words for Node.js via .NET.
  2. Add a library reference (import the library) to your JavaScript project.
  3. Open the source image file in JavaScript.
  4. Convert several image files into JPG in a few seconds.
  5. Call the appendDocument() method, passing an output filename with JPG extension.
  6. Get the result of conversion image into JPG.
🌐
products.aspose.com
products.aspose.com › aspose.words › node.js via .net › merge › image to jpg
Convert multiple image to JPG in JavaScript
What output file formats can I use to merge image files?
We support a variety of output file formats for image merging, including PDF, DOCX, DOC, HTML, RTF, Markdown, XML, ODT, JPG, PNG, TIFF, TXT and many more.
🌐
products.aspose.com
products.aspose.com › aspose.words › node.js via .net › merge › image to jpg
Convert multiple image to JPG in JavaScript
What is the maximum image size supported by Aspose.Words for Node.js via .NET?
There are no size limits to merge image files using Aspose.Words for Node.js via .NET.
🌐
products.aspose.com
products.aspose.com › aspose.words › node.js via .net › merge › image to jpg
Convert multiple image to JPG in JavaScript
🌐
CodePel
codepel.com › home › vanilla javascript › javascript convert png to jpg
JavaScript Convert Png To Jpg — CodePel
January 27, 2024 - Here is a free JavaScript code snippet to convert png image to jpg. Here you can view demo and download the source code.
Address   Rafi Qamar Road, Al-Majeed Peradise Al Majeed Peradise, 62300, Bahawalpur
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › how-to-convert-png-to-jpg-using-node-js
How to Convert PNG to JPG using Node.js ? - GeeksforGeeks
June 26, 2024 - Return the final JPG Image. Step 1: Initialize node.js project with the following command. ... Step 2: Install the required module using the following command. ... Step 3: Get one sample PNG file, for this example, we have taken the below image and placed it in the static folder. Step 4: Create an index.js file with the following code. ... // index.js // Import jimp module const Jimp = require("jimp"); // Read the PNG file and convert it to editable format Jimp.read("./static/GFG_IMG.png", function (err, image) { if (err) { // Return if any error console.log(err); return; } // Convert image to JPG and store it to // './output/' folder with 'out.jpg' name image.write("./output/out.jpg"); });
🌐
freeCodeCamp
freecodecamp.org › news › build-a-browser-based-image-converter-using-javascript
How to Build a Browser-Based Image Converter with JavaScript
March 23, 2026 - In this tutorial, you built a browser-based image converter using JavaScript. In this tutorial, you learned how to read local image files using JavaScript, process images using the Canvas API, convert them into different formats, and allow users to download the result directly from the browser.
🌐
GitHub
gist.github.com › mikey0000 › 5a078346f58713d0075f
convert png to jpeg using javascript and write back to original file · GitHub
convert png to jpeg using javascript and write back to original file · Raw · convertToJPG · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Find elsewhere
🌐
Code Boxx
code-boxx.com › home › convert image file format in javascript (jpg, png, webp, gif)
Convert Image File Format In Javascript (JPG, PNG, WEBP, GIF)
January 10, 2024 - All right, let us now get into more details about how the HTML Javascript image converter works. ... <form id="cForm" onsubmit="return convert.read()"> <label>SELECT FORMAT</label> <select id="cFormat"> <option value="webp">WEBP</option> <option value="jpeg">JPG</option> <option value="png">PNG</option> <option value="gif">GIF</option> </select> <label>CHOOSE FILE</label> <input type="file" id="cFile" accept="image/*" required> <input type="submit" value="Go"> </form>
🌐
GitHub
github.com › frumbert › png2jpeg-worker-js
GitHub - frumbert/png2jpeg-worker-js: a proof-of-concept javascript worker for converting png to jpeg, without using canvas · GitHub
var worker = new Worker("worker.js"); worker.onmessage = function(e) { var blob = new Blob([e.data.data], {type: 'image/jpeg'} ); var imageUrl = (window.URL || window.webkitURL).createObjectURL(blob); img = new Image(); img.src = imageUrl; document.querySelector("body").appendChild(img); } // in my example I'm reading all png files from the root of a zip file, converting them to jpeg, then displaying them on the body var zip = new JSZip(); // https://github.com/Stuk/jszip fetch("input.zip") .then(function(response) { return response.arrayBuffer(); }) .then(function(arraybuffer) { return zip.loadAsync(arraybuffer); }).then(function(zip) { zip.forEach(function(relativePath,file) { if (file.name.indexOf(".png") !== -1) { file.async("uint8array").then(function(data) { worker.postMessage({ image: data, quality: 70 }); }) } }); });
Author   frumbert
🌐
Apidog
apidog.com › blog › converting-images-to-jpeg-using-node-js-apidog
Converting Images to JPEG using Node.js & Apidog
July 29, 2025 - Now give the form data a name "Image", type "file", & upload the image to convert. Once done, click the Send button on the top right to send the request. If everything goes well, you should be able to see a 200 response and the file to download. It's important to note that when you download the file, you'll see a response.bin file. When you view the property, you'll find out it's a .jpg file.
Top answer
1 of 7
4

tl;dr: Don't bother

This might be theoretically possible, but I would recommend against it very strongly. It's possible to create a javascript Img element which refers to an URL the user has typed in. You can then draw this image in an HTML5 canvas.

You can then manually access the data on the canvas and analyze/convert the image to the approriate format. It might then be possible to send this Base64 or URL-encode to a server which could then return the image to the client.

This is of course completely crazy and should NOT be attempted. This solution would require implementing JPG compression in javascript which, although technically possible, is probably not feasible because of browser constraints (eg. speed).

2 of 7
4

Modern browser now provide the methods to convert images in the browser, if this is desired. The following method can be used on any browser that supports OffscreenCanvas and the required file types:

/**
 * Convert between any image formats the browser supports
 * @param {Blob} source A Blob (or File) containing the image to convert
 * @param {string} type The MIME type of the target format
 * @returns {Promise<Blob>} The converted image
 */
async function convert(source, type) {
    let image = await createImageBitmap(source);

    let canvas = new OffscreenCanvas(image.width, image.height);
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0);

    let result = await canvas.convertToBlob({ type });

    image.close();
    return result;
}

On browsers that don't support OffscreenCanvas, such as (as of January 2023) Safari, the following method can be used:

/**
 * Convert between any image formats the browser supports
 * @param {Blob} source A Blob (or File) containing the image to convert
 * @param {string} type The MIME type of the target format
 * @returns {Promise<Blob>} The converted image
 */
async function convertLegacy(source, type) {
    let image = await createImageBitmap(source);

    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;

    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0);

    let result = await new Promise((resolve, reject) => {
        canvas.toBlob((blob) => {
            if (blob != null) {
                resolve(blob);
            } else {
                reject(new Error("Failed to convert file"));
            }
        }, type, 1);
    });

    image.close();
    return result;
}

Note that the second method won't work in a WebWorker.

If an unsupported target format is given, the browser will default to PNG. There are probably no browser without JPEG support.

🌐
Medium
medium.com › @aeshghi › convert-jpg-images-to-png-using-html5-url-and-canvas-45b14ee853c9
Convert JPG images to PNG using HTML5 URL and Canvas | by Ardeshir Eshghi | Medium
February 16, 2017 - As you can see we have a very simple HTML file with the a file input called image. Next we add a script tag before body to write the JS code. So it will look like this: <!DOCTYPE html> <html> <head> ... </head> <body> ... <script> // code should go here </script></body> </html> Create an empty JS file and dump the below code into it: 'use strict'; const JpgToPngConvertor = (() =>{ function convertor(imageFileBlob, options) { options = options || {}; const defaults = {}; const settings = extend(defaults, options); const canvas = document.createElement('canvas'); const ctx = canvas.getContext("2d"); const imageEl = createImage(); const downloadLink = settings.downloadEl || createDownloadLink(); function createImage(options) { options = options || {}; const img = (Image) ?
🌐
Quora
quora.com › How-do-you-convert-a-jpg-image-to-png-using-JavaScript
How to convert a .jpg image to .png using JavaScript - Quora
Answer (1 of 3): Assuming you’re doing this in a browser, the process would go something like this: 1. Create an Image object. 2. Set its src to the URL of the JPEG. 3. Draw the Image on to a canvas. 4. Use the canvas context’s getImageData function to extract the raw pixel data.
🌐
GitHub
github.com › topics › image-converter
image-converter · GitHub Topics · GitHub
A 📁 file conversion app, you'll ever need. image-converter file-conversion hacktoberfest hacktoberfest2021 ... Save any image as PNG, JPG or WebP directly from the right-click menu.
🌐
Alexcorvi
alexcorvi.github.io › heic2any
Heic2any: Client-side conversion of HEIC/HEIF image files to JPEG, PNG, or GIF in the browser.
Client-side (browser-side, using Javascript) conversion of HEIC/HEIF image files to JPEG, PNG, or GIF.