Skip to content

Instantly share code, notes, and snippets.

@Meshiest
Created July 23, 2022 17:58
Show Gist options
  • Save Meshiest/ddd0bb2ff52724e74ddba280669e5bb2 to your computer and use it in GitHub Desktop.
Save Meshiest/ddd0bb2ff52724e74ddba280669e5bb2 to your computer and use it in GitHub Desktop.
randomize avatar colors
<h3>Select a .bp avatar to replace the colors in</h3>
<input id="fileInput" type="file" />
<a id="anchor" download="cloned.bp"></a>
<script>
fileInput.addEventListener('change', async e => {
const file = e.target.files[0];
if (!file) return;
const template = await file.text();
// srgb to linear rgb
const srgb2linear = c =>
Math.round(
(c / 255 > 0.04045
? Math.pow((c / 255) * (1.0 / 1.055) + 0.0521327, 2.4)
: (c / 255) * (1.0 / 12.92)) * 255
);
// random linear rgb
const rand = () => srgb2linear(Math.floor(Math.random() * 255));
// replace colors with new random colors
const generated = template.replace(
/\{(\s*\n\s*"[rbga]":\s*\d+,?\s*)+\n\s*\}/g,
r => {
return `{"r":${rand()},"g":${rand()},"b":${rand()},"a":255}`;
}
);
// encode template in url
const blob = new Blob([generated]);
anchor.href = URL.createObjectURL(blob);
anchor.download = file.name.replace(/\.bp$/, '-random.bp');
anchor.innerText = anchor.download;
// also log it to console
console.log(generated);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment