Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Download array of base64 images as ZIP file

I'm working in a Angular2 v4 app with Typescript and I need a way to download many images (in base64 format) into a Zip file.

For example: I have an array like this (fake base64 images just for example)

data = [
  'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA ...',
  'data:image/png;base64, iVBTYu0KGgoBBBBNSUhYUgJJJJUA ...',
  'data:image/png;base64, CGBHHFGY0goAAAANSUhEUgAAAAUA ...',
  ...
]

I need a way to download it converting each image to a .jpg or .png image first and then compile all images and dowload as a zip file. Something like this (I dont know the code, I just need something like this)

downloadZip() {
  const arrayAsJPG = [];
  this.data.forEach(i => {
    const imageInJpg = i.convertToJPGfile(); // this is not code, this is a function that converts the base64 to a jpg file
    arrayAsJPG.push(imageInJpg);
  });
  ZipFileSaver.save(arrayAsJPG, 'myImageReport.zip'); // this isn't code neither, just and interpretation of what I need

}

There is any way to make that?

like image 385
Sergio Mendez Avatar asked Dec 31 '22 18:12

Sergio Mendez


2 Answers

@gary gave a good explanation. I found a few examples on stackoverflow:

Is it possible to generate zip file and download in Angular 4?

Converting base64 to blob in javascript Can also use @types/jszip.

I builded an example that does the following:

  • It get the array as you described from an API (mock);
  • It convert each item of that array to an blob;
  • It add the blob as a file to the zip file;
  • And last create the zip file;
  • I only had png base64 so change that to jpg.

https://stackblitz.com/edit/angular-jzqtrk?file=src%2Fapp%2Fapp.component.ts

like image 132
Swoox Avatar answered Jan 08 '23 07:01

Swoox


You'll probably need to do this on a server in Node.

You have two questions here:

To convert the data string to an image

This is tough in the browser. You can render the data string as an img tag src and trigger a download of the image via javascript. I don't think you can write it to disk in the browser though so that a zip file utility can use it. This would be trivial in Node though.

To create a zip file

You should use an NPM package. Most are geared toward Node. You might have luck creating zip files directly in the browser using something like JSZip. Search Google for "npm zip" to see many other packages.

like image 38
Gary Avatar answered Jan 08 '23 07:01

Gary