Maybe string compression is the solution for you. This converts the data to byte arrays.

There are multiple implementations and algorithms around, for instance

  • LZMA-JS A standalone JavaScript implementation of the Lempel-Ziv-Markov chain (LZMA) compression algorithm.

    my_lzma = new LZMA("./lzma_worker.js");
    my_lzma.compress("This is my compression test.", 1, function on_compress_complete(result) {
        console.log("Compressed: " + result);
        my_lzma.decompress(result, function on_decompress_complete(result) {
            console.log("Decompressed: " + result);
        }, function on_decompress_progress_update(percent) {
            console.log("Decompressing: " + (percent * 100) + "%");
        });
    }, function on_compress_progress_update(percent) {
        console.log("Compressing: " + (percent * 100) + "%");
    });
    
  • lz-string: JavaScript compression, fast!

    var str = "This is my compression test.";
    console.log("Size of sample is: " + str.length);
    var compressed = LZString.compress(str);
    console.log("Size of compressed sample is: " + compressed.length);
    str = LZString.decompress(compressed);
    console.log("Sample is: " + str);
    
Answer from Koen. on Stack Overflow
Top answer
1 of 3
54

Maybe string compression is the solution for you. This converts the data to byte arrays.

There are multiple implementations and algorithms around, for instance

  • LZMA-JS A standalone JavaScript implementation of the Lempel-Ziv-Markov chain (LZMA) compression algorithm.

    my_lzma = new LZMA("./lzma_worker.js");
    my_lzma.compress("This is my compression test.", 1, function on_compress_complete(result) {
        console.log("Compressed: " + result);
        my_lzma.decompress(result, function on_decompress_complete(result) {
            console.log("Decompressed: " + result);
        }, function on_decompress_progress_update(percent) {
            console.log("Decompressing: " + (percent * 100) + "%");
        });
    }, function on_compress_progress_update(percent) {
        console.log("Compressing: " + (percent * 100) + "%");
    });
    
  • lz-string: JavaScript compression, fast!

    var str = "This is my compression test.";
    console.log("Size of sample is: " + str.length);
    var compressed = LZString.compress(str);
    console.log("Size of compressed sample is: " + compressed.length);
    str = LZString.decompress(compressed);
    console.log("Sample is: " + str);
    
2 of 3
13

I needed to generate thumbnails from larger pictures. I decided to solve my version of this problem with the HTML5 Canvas technique. I am using GWT so my code is:

//Scale to size
public static String scaleImage(Image image, int width, int height) {

    Canvas canvasTmp = Canvas.createIfSupported();
    Context2d context = canvasTmp.getContext2d();

    canvasTmp.setCoordinateSpaceWidth(width);
    canvasTmp.setCoordinateSpaceHeight(height);

    ImageElement imageElement = ImageElement.as(image.getElement());

    context.drawImage(imageElement, 0, 0, width, height);

    //Most browsers support an extra option for: toDataURL(mime type, quality) where quality = 0-1 double.
    //This is not available through this java library but might work with elemental version?
    String tempStr = canvasTmp.toDataUrl("image/jpeg");

    return tempStr;
}

If you are using JS you can probably get the idea:

  • Make a canvas the size of the desired output image
  • draw the input image on the canvas in the new size
  • call canvas.toDataURL("mime-type", quality)

You can use any mime-type I think, but for me the jpeg one was the smallest and was comparable to results of my desktop image program.

My GWT would not let me do the quality parameter (and I'm not 100% sure how widely supported it is in which browsers), but that was OK because the resulting images were quite small. If you leave the mime-type blank it defaults to png which in my case was 3-4x larger than jpeg.

🌐
Xano Developer Hub
community.xano.com › ask-the-community › post › is-there-a-way-to-compress-base64-images-WOj70d2OBG1hlUW
Is there a way to compress base64 images?
November 25, 2023 - Stability AI returns images in the base64 format. Which is incredibly long and heavy. I generated ~900 pictures, and they already take 2GB out of 3GB in my Xano workspace. Am I missing any efficient way to convert/compress base64 images?
Discussions

How to compress base64
Don't. Compress the underlying data. You also didn't explain what didn't work. "The problem is it didn't work". Yeah... . More on reddit.com
🌐 r/dotnet
8
0
March 26, 2023
how to compress a base64 image to custom size
I send/receive my image by using base64. I have a base64 string and I want to compress it to my size. for example I want to reduce photo size to 100kb. Is it possible? More on stackoverflow.com
🌐 stackoverflow.com
How do we compress the size of a base64 image in Node.js?
I receive a base64 encoded response from the api, which has huge no.of characters (data). So i want to scale/reduce the size of this base64 image. What's the best way to do that? More on stackoverflow.com
🌐 stackoverflow.com
c# - How to compress base64 string - Stack Overflow
If you are sending something like a jpeg-compressed image, you won't be able to compress it more, and it could even make the size larger. And if you have a 4MB jpeg file, you probably need to resize it to smaller pixel dimensions. ... @nithishpitla If you have a 4MB jpeg file, you probably need to resize it to smaller pixel dimensions. ... Save this answer. ... Show activity on this post. Base64 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
npm
npmjs.com › package › compress-base64
compress-base64 - npm
January 28, 2025 - import compress from 'compress-base64'; if (typeof FileReader === 'function') { const reader = new FileReader(); reader.onload = (event) => { compress(event.target.result, { width: 400, type: 'image/png', max: 200, // max size min: 20, // min size quality: 0.8, }).then((result) => { console.log(result); }); }; reader.readAsDataURL(file); } else { alert('Your browser does not support FileReader'); } Introduce this resource.
      » npm install compress-base64
    
Published: Apr 12, 2026
Version: 7.1.0
🌐
DEV Community
dev.to › konstantinstanmeyer › image-compression-in-javascripttypescript-dc9
Image Compression in JavaScript/TypeScript - DEV Community
December 4, 2023 - The following approach allows for increased file compression, inherently lowering file size as well as an added ability to store images in Base64-encoded strings if desired.
🌐
YouTube
youtube.com › giv
Reduce base64 image file size | JavaScript - YouTube
In this video I'll show you how you can reduce the file size of any image in base64 using JavaScript in the frontend before sending to server.Link to CODE: h...
Published: April 22, 2021
Views: 18K
Top answer
1 of 1
7

This was a fun challenge cuz it involved a binary search until it finds the right size. I'm not going to advice you to solve this with base64 instead of blob cuz you should really handle it as binary (blob) otherwise it takes up ~33% more data as base64

This code includes resizing that you can set a max width/hight and still be able to keep the aspect ratio and auto quality lookup until it finds the correct quality to match the MAX_SIZE

console.log('Downloading lorem ipsum image to simulate a file from user input')

fetch('https://picsum.photos/1920/1080/?random')
.then(res => res.blob())
.then(blob => {
  const img = new Image()
  img.src = URL.createObjectURL(blob)

  console.log(`Original image size (at 1920x1080) is: ${blob.size} bytes`)
  console.log('URL to original image:', img.src)
  
  img.onload = () => resize(img, 'jpeg').then(blob => {
    console.log('Final blob size', blob.size)
    console.log('Final blob url:', URL.createObjectURL(blob))

    console.log('\nNow with webp\n')

    resize(img, 'webp').then(blob => {
      console.log('Final blob size', blob.size)
      console.log('Final blob url:', URL.createObjectURL(blob))
    })
  })
}) 


const MAX_WIDTH = 1280
const MAX_HEIGHT = 720
const MAX_SIZE = 100000 // 100kb

async function resize(img, type = 'jpeg') {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  
  ctx.drawImage(img, 0, 0)
  
  let width = img.width
  let height = img.height
  let start = 0
  let end = 1
  let last, accepted, blob
  
  // keep portration
  if (width > height) {
    if (width > MAX_WIDTH) {
      height *= MAX_WIDTH / width
      width = MAX_WIDTH
    }
  } else {
    if (height > MAX_HEIGHT) {
      width *= MAX_HEIGHT / height
      height = MAX_HEIGHT
    }
  }
  canvas.width = width
  canvas.height = height
  console.log('Scaling image down to max 1280x720 while keeping aspect ratio')
  ctx.drawImage(img, 0, 0, width, height)
  
  accepted = blob = await new Promise(rs => canvas.toBlob(rs, 'image/'+type, 1))
  
  if (blob.size < MAX_SIZE) {
    console.log('No quality change needed')
    return blob
  } else {
    console.log(`Image size after scaling ${blob.size} bytes`)
    console.log('Image sample after resizeing with losseless compression:', URL.createObjectURL(blob))
  }
  
  // Binary search for the right size
  while (true) {
    const mid = Math.round( ((start + end) / 2) * 100 ) / 100
    if (mid === last) break
    last = mid
    blob = await new Promise(rs => canvas.toBlob(rs, 'image/'+type, mid))
        console.log(`Quality set to ${mid} gave a Blob size of ${blob.size} bytes`)
    if (blob.size > MAX_SIZE) { end = mid }
    if (blob.size < MAX_SIZE) { start = mid; accepted = blob }
  }

  return accepted
}

PS/warning Canvas don't do any good compression, if you paint a jpg picture on a canvas element and get the image back with no resizing, manipulation quality loss or changing the format toBlob('image/jpg', cb, 1) then you will most definitely get a larger file back since they probably already are well compressed and canvas dose none. I only change the quality & max width/height to reduce the size with the canvas api. You would need some compressor to reduce it even more without quality loss.

Another thing you will lose are some image metadata like geolocation and other useful EXIF data. maybe you want that or you don't

  • jsfiddle demonstration of file increase with canvas
  • imageoptim
  • squoosh.app
  • zopfli
  • pngcrush
🌐
Base64Encode.org
base64encode.org › enc › compress
Base64 Encoding of "compress" - Online
The particular choice of characters to make up the 64 characters required for Base64 varies between implementations. The general rule is to choose a set of 64 characters that is both 1) part of a subset common to most encodings, and 2) also printable. This combination leaves the data unlikely to be modified in transit through systems such as email, which were traditionally not 8-bit clean.
Find elsewhere
🌐
Quora
quora.com › How-can-I-make-sure-the-converted-base64-image-data-is-always-below-1mb-I-have-compressed-image-to-below-720p-but-sometimes-base64-data-becomes-over-1mb
How can I make sure the converted base64 image data is always below 1mb? I have compressed image to below 720p but sometimes base64 data ...
Answer (1 of 2): What is the codec? . (base64 is just a wrapper encoding). If it is png, you don't have many options. There is PAETH, and zlib MAX compression. You can also take an RGBA or RGB and palletize down to U8. But then you pretty much just have a GIF. But it's pretty much lossless, so n...
🌐
B64
b64.io
b64.io - image optimisation & base64 encode
Upload your image(s) on b64.io : we optimize and encode in base64.
🌐
Medium
vips3201v.medium.com › image-compression-in-javascript-image-to-base64-encoder-b74c1c8e0464
Image Compression in JavaScript : Image to base64 encoder | by Vipasha Vaghela | Medium
February 4, 2021 - Image compression is a type of data compression applied to images, to reduce their cost for storage or transmission Base64 is a binary-to-text encoding scheme. It represents binary data in a printable ASCII string format by translating it into a radix-64 representation.
🌐
Base64 Image Encoder
base64-image.de
Convert Images to Base64 Online — Free Encoder & Optimizer | base64-image.de
This tool supports all common web image formats: JPEG, PNG, GIF, WebP, SVG, BMP, ICO, TIFF, AVIF, and HEIC/HEIF. Each format can be compressed before encoding to reduce the base64 output size.
🌐
GitHub
gist.github.com › profiprog › 88327d5cb4599b1370d1252d262dd42e
Simple compressing base64 string in JavaScript · GitHub
You are right @Rubioli, compressed result can easily be longer than the original. The compression rate depends on the data you have. This one is suitable only for images where bites are repeating many times. PNG is also using this characteristic, so it would never be suitable for this compression method.
Top answer
1 of 2
1

Well, base64 is just a text representation of some bytes.

First, you need to transform it into the buffer with bytes. E.g. like this:

const imageBuffer = Buffer.from(yourString, 'base64');

Then you should either save it on a disk and use some other tools like imagemagick to transform it:

fs.writeFileSync('your-image.png', imageBuffer); // in case you know it's PNG, ofc
// transform somehow, probably invoking third-party tool using child_process.execSync

Or you may use libs like Sharp to optimize the image in that buffer. Here's an example from the repo:

sharp(inputBuffer)
  .resize(320, 240)
  .toFile('output.webp', (err, info) => { ... });

Depending on the type of the image you manipulate and on the transformations you're trying to do, you may need different tools, not only Sharp, but also Gifsicle or Guetzli.

Years ago my team created a small CLI tool for optimizing images for our needs. The tool does not solve your problem, but maybe its code, where we work with different encoders, can help you somehow:

https://github.com/funbox/optimizt/blob/master/lib/optimize.js

2 of 2
0

Install library npm install sharp

Conversion to image, resize as you need, and then convert to base64

let arrData = `${imageBase64}`.split(',');
var imgBuffer = Buffer.from(arrData[1], 'base64');
const sharp = require('sharp');
let bufferImgCompressed = await sharp(imgBuffer)
.resize({ width: 100, height: 200 })
.toBuffer()
.then(data => { return data; })
.catch(err => { console.log('Error on compress'); });

let imgBase64Compressed = bufferImgCompressed.toString('base64');

The use of ${imageBase64}.split(',') is because to convert base64 to buffer the string should not to contains the 'data:image/...'

🌐
Base64.Guru
base64.guru › home › base64 converter › base64 encode
Image to Base64 | Base64 Encode | Base64 Converter | Base64
Convert image to Base64 online and use the result string as data URI, img src, CSS background-url, and others. Sometimes you have to send or output an image within a text document (for example, HTML, CSS, JSON, XML), but you cannot do this because binary characters will damage the syntax of the text document.
🌐
Base64 Encode
base64encode.net › encode › b1WH
Base64 Encode: compressor
The common concept is to select a set of 64 characters that is both part of a subset typical to most encodings. This mixture leaves the data impossible to be altered in transportation thru information systems, such as electronic mail, that were typically not 8-bit clean. The Base64 implementation in MIME uses a-z, A-Z and 0-9 for the first 62 values.
🌐
Compresto
compresto.app › home › blog › image to base64: how to encode images (and when you shouldn't)
Image to Base64: How to Encode Images (and When You Shouldn't)
June 30, 2026 - Base64 inflates whatever you feed ... is the cleanest way to do this: drop in your PNG or JPEG, compress it with hardware-accelerated optimization, and then encode the slimmed-down output....