Created
May 18, 2021 15:05
-
-
Save jpthewes/65c6d3da1517da7c299251bee0338608 to your computer and use it in GitHub Desktop.
SVG file altering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
onFileChange(ev: any) { | |
var data_uri = new String; | |
// asuming that only 1 file is uploaded | |
const file = ev.target.files[0]; | |
// Check file size | |
if (file.size > <SILE_LIMIT>) { | |
// do your feedback | |
return; | |
} | |
new Promise((resolve, reject) => { | |
const reader = new FileReader(); | |
// onload event triggered after data from readAsXXX is available | |
reader.onerror = reject; | |
reader.onload = e => { | |
if (file.type == "image/svg+xml") { | |
const parser = new DOMParser(); | |
const serializer = new XMLSerializer(); | |
var doc = parser.parseFromString(<string>e.target.result, "image/svg+xml"); | |
// check if height or width contains a % sign OR do any other check here | |
if ((/%/.test(doc.documentElement.getAttribute("width"))) || /%/.test(doc.documentElement.getAttribute("height"))) { | |
doc.documentElement.setAttribute("width", doc.documentElement.getAttribute("viewBox").split(" ")[2]); | |
doc.documentElement.setAttribute("height", doc.documentElement.getAttribute("viewBox").split(" ")[3]); | |
} | |
resolve("data:image/svg+xml;base64," + btoa(serializer.serializeToString(doc))) | |
} else { | |
resolve(<string>e.target.result) | |
} | |
} | |
if (file.type == "image/svg+xml") { | |
reader.readAsText(file); | |
} else { | |
reader.readAsDataURL(file); | |
} | |
}).then((data_uri) => this.parentForm.controls[<form_field_name>].setValue(data_uri)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment