shrink the size of a image in vanilla javascript in javascript

To shrink the size of an image in vanilla JavaScript, you can use the HTML canvas element. The steps are as follows:

  1. Create a new Image object and set its src attribute to the URL of the image you want to shrink.
index.tsx
var img = new Image();
img.src = 'path/to/image.jpg';
54 chars
3 lines
  1. When the image has finished loading, create a new canvas element and its context (2D), then set the dimensions of the canvas to the desired smaller size.
index.tsx
img.onload = function () {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  canvas.width = 200; // new width
  canvas.height = 150; // new height
185 chars
6 lines
  1. Draw the original image onto the canvas context and use the drawImage method, specifying the original Image object and the dimensions of the new shrunk image.
index.tsx
  ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
86 chars
2 lines
  1. Then, you can get the new shrunk image in the form of a data URL using the canvas toDataURL() method, which encodes the image as a base64 data string, as shown below.
index.tsx
  var shrunkImage = canvas.toDataURL('image/jpeg', 0.5); // specify the image format and quality
};
100 chars
3 lines

The final code would look like this:

index.tsx
var img = new Image();
img.src = 'path/to/image.jpg';

img.onload = function () {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  canvas.width = 200; // new width
  canvas.height = 150; // new height

  ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

  var shrunkImage = canvas.toDataURL('image/jpeg', 0.5); // specify the image format and quality
};
428 chars
14 lines

gistlibby LogSnag