resize image before storing (#831)

* resize image fn

* wip

* simplify transform

* comment

* fix

* rm log

* allow pass-through for non-base-64

Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
Alex JohanssonandAlex van Andel authored and GitHub committed 2021-09-30 21:37:29 +01:00
1 parent e33962686e
commit 60298f6eeb
5 files changed
+511 -6

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
import jimp from "jimp";
export async function resizeBase64Image(
base64OrUrl: string,
opts?: {
maxSize?: number;
}
) {
if (!base64OrUrl.startsWith("data:")) {
// might be a `https://` or something
return base64OrUrl;
}
const mimeMatch = base64OrUrl.match(/^data:(\w+\/\w+);/);
const mimetype = mimeMatch?.[1];
if (!mimetype) {
throw new Error(`Could not distinguish mimetype`);
}
const buffer = Buffer.from(base64OrUrl.replace(/^data:image\/\w+;base64,/, ""), "base64");
const {
// 96px is the height of the image on https://cal.com/peer
maxSize = 96 * 4,
} = opts ?? {};
const image = await jimp.read(buffer);
if (image.getHeight() !== image.getHeight()) {
// this could be handled later
throw new Error("Image is not a square");
}
const currentSize = Math.max(image.getWidth(), image.getHeight());
if (currentSize > maxSize) {
image.resize(jimp.AUTO, maxSize);
}
const newBuffer = await image.getBufferAsync(mimetype);
return `data:${mimetype};base64,${newBuffer.toString("base64")}`;
}
+4
View File
@@ -8,6 +8,7 @@ import { checkRegularUsername } from "@lib/core/checkRegularUsername";
import slugify from "@lib/slugify";
import { createProtectedRouter } from "../createRouter";
import { resizeBase64Image } from "../lib/resizeBase64Image";
const checkUsername =
process.env.NEXT_PUBLIC_APP_URL === "https://cal.com" ? checkPremiumUsername : checkRegularUsername;
@@ -119,6 +120,9 @@ export const viewerRouter = createProtectedRouter()
}
}
}
if (input.avatar) {
data.avatar = await resizeBase64Image(input.avatar);
}
await prisma.user.update({
where: {