Skip to content

Instantly share code, notes, and snippets.

@Flyrell
Created February 10, 2020 18:00
Show Gist options
  • Save Flyrell/8845d92c3b015521b33e857731c50c9e to your computer and use it in GitHub Desktop.
Save Flyrell/8845d92c3b015521b33e857731c50c9e to your computer and use it in GitHub Desktop.
Code used to upload the file and create an avatar of a fixed size from the center of the uploaded image. Keeps the original ratio of an image and makes sure dimensions of the images are at least the same as our fixed size.
const AVATAR_SIZE = 140;
function onFileChange(input: HTMLInputElement): Promise<string> {
const fileReader = new FileReader();
fileReader.readAsDataURL(input.files.item(0));
return new Promise((resolve) => {
fileReader.onload = (event) => {
const image = new Image();
image.src = event.target.result as string;
image.onload = () => {
const ratio = image.naturalWidth / image.naturalHeight;
const isLandscape = ratio > 1;
const width: number = isLandscape ? size * ratio : size;
const height: number = isLandscape ? size : size / ratio;
const imageX: number = isLandscape ? width / -4 : 0;
const imageY: number = isLandscape ? 0 : height / -4;
const canvas = this.document.createElement('canvas');
canvas.width = AVATAR_SIZE;
canvas.height = AVATAR_SIZE;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, imageX, imageY, width, height);
resolve(ctx.canvas.toDataURL( 'image/jpeg', 0.8));
};
};
});
}
<input type="file" accept="image/*" onchange="onFileChange(this)">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment