mirror of
https://github.com/hex248/sprint.git
synced 2026-02-07 18:23:03 +00:00
gif avatar support
all resizing is done server-side with sharp
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { getAuthHeaders, getServerURL, resizeImageToSquare } from "@/lib/utils";
|
||||
import { getAuthHeaders, getServerURL } from "@/lib/utils";
|
||||
import type { ServerQueryInput } from "..";
|
||||
|
||||
export async function uploadAvatar({
|
||||
@@ -21,17 +21,8 @@ export async function uploadAvatar({
|
||||
return;
|
||||
}
|
||||
|
||||
let resizedFile: File;
|
||||
try {
|
||||
const blob = await resizeImageToSquare(file, 256);
|
||||
resizedFile = new File([blob], "avatar.png", { type: "image/png" });
|
||||
} catch (_error) {
|
||||
onError?.("Failed to resize image");
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("file", resizedFile);
|
||||
formData.append("file", file);
|
||||
|
||||
const res = await fetch(`${getServerURL()}/user/upload-avatar`, {
|
||||
method: "POST",
|
||||
|
||||
@@ -31,45 +31,3 @@ export function getServerURL() {
|
||||
}
|
||||
return serverURL;
|
||||
}
|
||||
|
||||
export async function resizeImageToSquare(file: File, targetSize: number = 256): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
const canvas = document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
|
||||
if (!ctx) {
|
||||
reject(new Error("Could not get canvas context"));
|
||||
return;
|
||||
}
|
||||
|
||||
img.onload = () => {
|
||||
canvas.width = targetSize;
|
||||
canvas.height = targetSize;
|
||||
|
||||
const minDimension = Math.min(img.width, img.height);
|
||||
const startX = (img.width - minDimension) / 2;
|
||||
const startY = (img.height - minDimension) / 2;
|
||||
|
||||
ctx.drawImage(img, startX, startY, minDimension, minDimension, 0, 0, targetSize, targetSize);
|
||||
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (blob) {
|
||||
resolve(blob);
|
||||
} else {
|
||||
reject(new Error("Failed to create blob"));
|
||||
}
|
||||
},
|
||||
"image/png",
|
||||
0.9,
|
||||
);
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
reject(new Error("Failed to load image"));
|
||||
};
|
||||
|
||||
img.src = URL.createObjectURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user