|
@@ -0,0 +1,73 @@
|
|
|
+export const imageRotate = async (
|
|
|
+ url: string,
|
|
|
+ direction: "row" | "column" = "row"
|
|
|
+): Promise<void | Blob> => {
|
|
|
+ const img = new Image();
|
|
|
+ img.src = url;
|
|
|
+ await new Promise((resolve) => (img.onload = resolve));
|
|
|
+
|
|
|
+ let width = img.width;
|
|
|
+ let height = img.height;
|
|
|
+ if (width > height) {
|
|
|
+ if (direction === "row") {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ width = img.height;
|
|
|
+ height = img.width;
|
|
|
+ } else {
|
|
|
+ if (direction === "column") {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ width = img.height;
|
|
|
+ height = img.width;
|
|
|
+ }
|
|
|
+
|
|
|
+ const canvas = document.createElement("canvas");
|
|
|
+ canvas.width = width;
|
|
|
+ canvas.height = height;
|
|
|
+ const ctx = canvas.getContext("2d")!;
|
|
|
+
|
|
|
+ const center =
|
|
|
+ direction === "row"
|
|
|
+ ? [img.width / 2, height / 2]
|
|
|
+ : [img.height / 2, width / 2];
|
|
|
+ ctx.translate(center[0], center[1]);
|
|
|
+ ctx.rotate(((direction === "row" ? -1 : 1) * Math.PI) / 2);
|
|
|
+ ctx.translate(-center[0], -center[1]);
|
|
|
+ ctx.drawImage(img, 0, 0);
|
|
|
+
|
|
|
+ return await new Promise<Blob>((resolve) =>
|
|
|
+ canvas.toBlob(resolve as any, "image/png", 1)
|
|
|
+ );
|
|
|
+};
|
|
|
+
|
|
|
+export const fixImageSize = async (blob: Blob, max: number, min: number) => {
|
|
|
+ const img = new Image();
|
|
|
+ img.src = URL.createObjectURL(blob);
|
|
|
+ await new Promise((resolve) => (img.onload = resolve));
|
|
|
+
|
|
|
+ let width = img.width;
|
|
|
+ let height = img.height;
|
|
|
+ if (width > max) {
|
|
|
+ height = (height / width) * max;
|
|
|
+ width = max;
|
|
|
+ } else if (height > max) {
|
|
|
+ width = (width / height) * max;
|
|
|
+ width = max;
|
|
|
+ }
|
|
|
+ let size = width > height ? width : height;
|
|
|
+ size = size > min ? size : min;
|
|
|
+ const $canvas = document.createElement("canvas");
|
|
|
+ $canvas.width = size;
|
|
|
+ $canvas.height = size;
|
|
|
+ const ctx = $canvas.getContext("2d")!;
|
|
|
+ ctx.rect(0, 0, size, size);
|
|
|
+ ctx.fillStyle = "#fff";
|
|
|
+ ctx.fill();
|
|
|
+ ctx.drawImage(img, (size - width) / 2, (size - height) / 2, width, height);
|
|
|
+
|
|
|
+ const newBlob = await new Promise<Blob | null>((resolve) =>
|
|
|
+ $canvas.toBlob(resolve, "png")
|
|
|
+ );
|
|
|
+ return newBlob;
|
|
|
+};
|