Skip to content

Instantly share code, notes, and snippets.

@tonis2
Created April 26, 2018 11:54
Show Gist options
  • Save tonis2/324746c33d18120f54364ad652d7bde6 to your computer and use it in GitHub Desktop.
Save tonis2/324746c33d18120f54364ad652d7bde6 to your computer and use it in GitHub Desktop.
Replace data:image urls in JSON
import fs from "fs";
import uuid from "uuid/v1";
const replaceDataImg = (string) => {
const data = string.replace(/^data:image\/\w+;base64,/, "");
const buf = new Buffer(data, 'base64');
const name = `server/files/${uuid()}.png`;
fs.writeFile(name, buf, (error) => { if(error) console.log("Error!", error)});
return `"${name}"`;
}
const replaceImagesInHTML = (html) => {
const regex = /"data:image\/([a-zA-Z]*);base64,([^\"]*)\"/g;
const images = html.match(regex);
images.forEach(img => {
const newImg = replaceDataImg(JSON.parse(img));
html = html.replace(img, newImg);
});
return html;
}
export {replaceImagesInHTML}
@tonis2
Copy link
Author

tonis2 commented Apr 26, 2018

I use this to send HTML json with data:image as tags src-es then in backend i replace the data:image with real .png image file location.

And boom you can load the HTML and it contains tags with file urls instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment