What is the best way to reduce the size of a Base64/Binary image in Angular6

I utilized the Ngx-Webcam tool to capture images from my camera. My goal is to obtain both high quality and low quality images from the camera.

Although this library provides me with Base64 images, it offers an option to reduce the size using imageQuality. However, I cannot use this feature as I require both high quality and low quality images.

let data = webcamImage.imageAsBase64;
const raw = window.atob(data);

const rawLength = raw.length;
const unit8array = new Uint8Array(new ArrayBuffer(rawLength));

for (let i = 0; i < rawLength; i++) {
  unit8array[i] = raw.charCodeAt(i);
}

I attempted to implement a solution using https://www.npmjs.com/package/image-conversion for our issue.

let data = webcamImage.imageAsBase64;
const raw = window.atob(data);
let contentType = raw.split(';')[0];

const rawLength = raw.length;
const unit8array = new Uint8Array(new ArrayBuffer(rawLength));

for (let i = 0; i < rawLength; i++) {
  unit8array[i] = raw.charCodeAt(i);
}

let blob = new Blob([unit8array], {type: contentType});
imageProcess.compress(blob, 0.4);

Unfortunately, this approach did not work. I am now seeking another solution to compress the image.

Answer №1

I discovered a method to compress images using canvas

compress(webcamImage: WebcamImage, quality: number): Observable<string> {
  let _canvas = this.canvas;
  let width = webcamImage.width;
  let height = webcamImage.height;

  _canvas.width = width;
  _canvas.height = height;

  // drawing snapshot image on canvas
  const img = new Image();
  img.src = webcamImage.imageAsDataUrl;
  return Observable.create(observe => {
    (img.onload = () => {
      const context2d = _canvas.getContext('2d');
      context2d.drawImage(img, 0, 0, width, height);
      // converting canvas content to compressed image
      const mimeType: string = webcamImage.mineType;
      const dataUrl: string = _canvas.toDataURL(mimeType, quality);
      observe.next(dataUrl);
    });
  });
}

Answer №2

The image in base64 format is likely already compressed as a jpeg before being encoded. Further compression of this data is not possible.

If you require both high and low quality versions of the image, consider requesting a high-quality (preferably raw pixel) image from the webcam and converting it into jpeg images with varying compression parameters.

If the camera only provides jpeg data, you will need to decompress and recompress it with different parameters, although this process may take longer and result in lower quality.

Ngx-webcam may have limitations for meeting this particular need, so it might be necessary to modify its code to capture images at various quality levels. The captureImageData flag can be used to access raw image data, but the documentation on how to use it effectively may be lacking.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on how to showcase various information in distinct tabs using VueJS

I am currently working on a website project utilizing the VueJS framework and Vuetify template. My goal is to showcase different content under separate tabs, however, I'm encountering an issue where the same content is being displayed in all three tab ...

The dependencies were not updated after running `npm install`

When attempting to update the dependencies in my react-native CLI app by running npm install for the package.json, I encountered issues. Subsequently, I tried using npm audit fix and npm audit fix --force without success. In an effort to resolve the probl ...

What is the correct method to properly encode JSON that may include HTML when displaying it in an HTML file?

After searching through numerous questions, none seem to address this specific scenario. app.get('/', function(req, res) { res.set('Content-Type', 'text/html'); res.send(`<html> <body> Hello, World! </body&g ...

I am currently struggling with a Typescript issue that I have consulted with several individuals about. While many have found a solution by upgrading their version, unfortunately, it

Error message located in D:/.../../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts TypeScript error in D:/.../.../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts(1,13): Expecting '=', TS1005 1 | import type { Reducer, ReducersMapO ...

Mocking multiple services and their constructors in an Angular 2 TypeScript Jasmine test component

I've got this login component code snippet that I need help testing in Angular. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@ ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

Oh no, an issue has occurred with The Angular Compiler! It appears that TypeScript version 3.9.10 was found instead of the required version, which should be >=3.6.4 and <

After upgrading my angular application from version 5 to version 9, I encountered an issue while trying to deploy my code on the server. ERROR in The Angular Compiler requires TypeScript >=3.6.4 and <3.9.0 but 3.9.10 was found instead. Even though ...

Detecting changes in parent ref with Vue's v-modelIs this

I am struggling to implement two-way binding because I can't determine if the model ref is being changed by the parent or child component. Using watch captures all changes without any indication of the source of the change. <script setup> // Pa ...

Tips for implementing a button redirection to a different page using React

I am facing an issue with a component that includes a function onClick in its Class.propTypes: onClick: PropTypes.func Within another component, I have used this particular component multiple times to populate a page. Each instance of these components con ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

Why are the indicators and controls for Twitter-Bootstrap 5 carousel not functioning properly?

Currently, I am working on developing an ecommerce website using the Django framework. However, I am facing challenges with making my bootstrap carousel function properly. When trying to interact with the indicators and controls, nothing happens as expect ...

Increasing the variable by 1 in PHP will result in the variable value being incremented to 1

My issue involves incrementing a variable in my .php file code that changes the value in the database. After incrementing the acc_points variable by one, it updates the data in the MySQL database and then returns the data to the JavaScript, which alerts th ...

Having trouble uploading a file to Laravel using the jQuery .post method?

Here is a snippet of my HTML code: <input type="file" class="form-control" name="file-name" id="file-id"> This is the JavaScript function that is meant to send the file to an API: var file = $('input#file-id').val(); $.post('my/url/ ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

Redirect in React Route

I've been researching how to programmatically redirect in React, but I'm struggling to get it to work. Here's a simplified version of my code: import React from 'react'; import {render} from 'react-dom'; import {Browser ...

Refresh a Particular Section of a Website Without Having to Reload the Entire Page

I have this PHP script that I'm using to read specific phrases from a text file and then display one of them randomly on a webpage. Currently, the only way to see a new random phrase is by refreshing the entire page. I'm wondering if there is a w ...

I'm still searching for a proper solution on how to access JavaScript/jQuery functions within Colorbox

For my website, I am utilizing PHP, jQuery/JavaScript, Colorbox (a jQuery lightbox plugin), Smarty, and other tools. Currently, I am working on displaying data in a popup using the Colorbox plugin. However, I am facing an issue with calling a JavaScript fu ...

Encountering an issue of receiving "Undefined" while attempting to access constant data from a ReactJS file within my NodeJS

I am currently working on a file named check-rates that stores useStates() which are inputs provided by users. These inputs are essential for me to calculate and provide an estimated value for their shipment using the DHL API. In my nodejs express server, ...