Tag: javascript

input file: how to manipulate an image before uploading

input file: how to manipulate an image before uploading

UPDATE 2017 July 2st
I’ve fixed the source code in order to solve a couple of bug:
1) Files with no exif data crashes the app
2) new Files() on iphone brakes the upload,  formData contains empty files

——

I built an angular2+ component that allows selecting and previewing single images before uploading them through an api.
The component works fine with angular forms.
When the user selects a picture, it often happens that it is not correctly oriented, especially if the picture is taken on the fly from the mobile camera.

The solution is made of three steps:

  1.  Read the exif data and get the orientation
  2.  Accordingly with the orientation, rotate the image by using canvas
  3.  Update the “file” object

In this article I am going to focus on these steps, in a further one, I’d like to  discuss about the whole component (that works with angular form by implementing ControlValueAccessor)

For the steps 1 and 2 I’ve written a little angular provider in order to have a base on which I can add other canvas methods:
(Read the comments in the code below)

After we’ve integrated this provider, we just have to call its methods and update our “file” object
I use  FileReader() in order to show the preview, so I modify the image as soon as I load it.

 

How to calculate the file size from a base64 string in javascript

How to calculate the file size from a base64 string in javascript

A base64 string looks like this:
data:​image/​png;​base64,iVBORw0KGgoAAAANSUhEUg[…]

To calculate the size you have to:

  1. remove the header (data:​image/​png;​base64,)
  2. remove the “=” chars used as padding
  3. multiply for 3/4

The code: