Alter SVG Content at file loading in Javascript/Angular

Jan-Philipp Thewes
2 min readMay 18, 2021

This post will go into the problem of how you can check for specific SVG content and also alter it whilst loading the file — to be made compatible with ngx-image-cropper. If you just want to see the code and see if it help you, just jump ahead.

W3C SVG Logo
W3C SVG Logo

Context: Assume you have a frontend in which you want to give the user the possibility to upload images. With this there always comes the question which file formats you want to support. In my case I also wanted to support svg but my image cropper package did not handle that for various reasons.

Assumptions: I assume you have already built an upload possibility for your frontend and just want to adapt to SVG file format. My examples are in Angular but the main part of the SVG alteration is pure Javascript.

In Angular you can define a method which handles the file change event upon a user upload. In this example onFileChange() handles this event:

<input
#inputBox
(change)="onFileChange($event)"
.... //other tags
accept="image/*"
class="w-100"fullWidth
nbInput
type="file">

In the onFileChange() method the file reading and form filling of the user selected file is defined. In this simple example the assumption is made, that only one file is being uploaded.

In the code gist you can see that you can do various checks depending on the file type. Furthermore you can then do some modifications to the SVG file depending on its properties before converting it into a Data-URI like for the other file formats. The parsing is done using DOMParser, while the serialization is done with XMLSerializer. Both are standard packages. Promise is used to ensure the correct order of execution.

My specific problem here was ensuring that the width and height properties are set in the SVG file — or rather it’s base64 encoding — for the ngx-image-cropper to load it properly, but I am sure the SVG data manipulation can also be useful in other use cases. I hope I could help you out with this little article!

--

--