Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

optimize image uploads

Steven Tey369db65ba4f8
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 9fed17f19e..bc920766b4 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -555,7 +555,10 @@ export async function addLink(link: LinkWithTagIdsProps) {
if (proxy && image && !isStored(image)) {
await Promise.all([
// upload image to R2
- storage.upload(`images/${response.id}`, image),
+ storage.upload(`images/${response.id}`, image, {
+ width: 1200,
+ height: 630,
+ }),
// update the null image we set earlier to the uploaded image URL
prisma.link.update({
where: {
@@ -746,7 +749,10 @@ export async function editLink({
if (proxy && image && !isStored(image)) {
// only upload image if proxy is true and image is not stored in R2
- await storage.upload(`images/${id}`, image);
+ await storage.upload(`images/${id}`, image, {
+ width: 1200,
+ height: 630,
+ });
// if there's an image in R2, delete it
} else if (oldImage?.startsWith(process.env.STORAGE_BASE_URL as string)) {
await storage.delete(`images/${id}`);
diff --git a/apps/web/lib/images.ts b/apps/web/lib/images.ts
new file mode 100644
index 0000000000..3322905a2e
--- /dev/null
+++ b/apps/web/lib/images.ts
@@ -0,0 +1,75 @@
+export const resizeImage = (
+ file: File,
+ opts: {
+ width: number;
+ height: number;
+ quality: number;
+ } = {
+ width: 1200, // Desired output width
+ height: 630, // Desired output height
+ quality: 1.0, // Set quality to maximum
+ },
+): Promise<string> => {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = (e: ProgressEvent<FileReader>) => {
+ const img = new Image();
+ img.src = e.target?.result as string;
+ img.onload = () => {
+ const targetWidth = opts.width;
+ const targetHeight = opts.height;
+ const canvas = document.createElement("canvas");
+ canvas.width = targetWidth;
+ canvas.height = targetHeight;
+
+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
+ ctx.imageSmoothingQuality = "high"; // Set image smoothing quality to high
+
+ // Calculating the aspect ratio
+ const sourceWidth = img.width;
+ const sourceHeight = img.height;
+ const sourceAspectRatio = sourceWidth / sourceHeight;
+ const targetAspectRatio = targetWidth / targetHeight;
+
+ let drawWidth: number;
+ let drawHeight: number;
+ let offsetX = 0;
+ let offsetY = 0;
+
+ // Adjust drawing sizes based on the aspect ratio
+ if (sourceAspectRatio > targetAspectRatio) {
+ // Source is wider
+ drawHeight = sourceHeight;
+ drawWidth = sourceHeight * targetAspectRatio;
+ offsetX = (sourceWidth - drawWidth) / 2;
+ } else {
+ // Source is taller or has the same aspect ratio
+ drawWidth = sourceWidth;
+ drawHeight = sourceWidth / targetAspectRatio;
+ offsetY = (sourceHeight - drawHeight) / 2;
+ }
+
+ // Draw the image onto the canvas
+ ctx.drawImage(
+ img,
+ offsetX,
+ offsetY,
+ drawWidth,
+ drawHeight,
+ 0,
+ 0,
+ targetWidth,
+ targetHeight,
+ );
+
+ // Convert the canvas to a base64 string
+ const base64Image = canvas.toDataURL("image/jpeg", opts.quality);
+ resolve(base64Image);
+ };
+ img.onerror = (error) =>
+ reject(new Error("Image loading error: " + error));
+ };
+ reader.onerror = (error) => reject(new Error("FileReader error: " + error));
+ reader.readAsDataURL(file);
+ });
+};
diff --git a/apps/web/lib/storage.ts b/apps/web/lib/storage.ts
index 167bc25604..8572101677 100644
--- a/apps/web/lib/storage.ts
+++ b/apps/web/lib/storage.ts
@@ -1,5 +1,12 @@
+import { fetchWithTimeout } from "@dub/utils";
import { AwsClient } from "aws4fetch";
+interface imageOptions {
+ contentType?: string;
+ width?: number;
+ height?: number;
+}
+
class StorageClient {
private client: AwsClient;
@@ -12,17 +19,13 @@ class StorageClient {
});
}
- async upload(
- key: string,
- body: Blob | Buffer | string,
- contentType?: string,
- ) {
+ async upload(key: string, body: Blob | Buffer | string, opts?: imageOptions) {
let uploadBody;
if (typeof body === "string") {
if (this.isBase64(body)) {
- uploadBody = this.base64ToArrayBuffer(body, contentType);
+ uploadBody = this.base64ToArrayBuffer(body, opts);
} else if (this.isUrl(body)) {
- uploadBody = await this.urlToBlob(body, contentType);
+ uploadBody = await this.urlToBlob(body, opts);
} else {
throw new Error("Invalid input: Not a base64 string or a valid URL");
}
@@ -33,7 +36,7 @@ class StorageClient {
const headers = {
"Content-Length": uploadBody.size.toString(),
};
- if (contentType) headers["Content-Type"] = contentType;
+ if (opts?.contentType) headers["Content-Type"] = opts.contentType;
try {
await this.client.fetch(`${process.env.STORAGE_ENDPOINT}/${key}`, {
@@ -58,7 +61,7 @@ class StorageClient {
return { success: true };
}
- private base64ToArrayBuffer(base64: string, contentType?: string) {
+ private base64ToArrayBuffer(base64: string, opts?: imageOptions) {
const base64Data = base64.replace(/^data:.+;base64,/, "");
const paddedBase64Data = base64Data.padEnd(
base64Data.length + ((4 - (base64Data.length % 4)) % 4),
@@ -70,9 +73,9 @@ class StorageClient {
for (let i = 0; i < binaryString.length; i++) {
byteArray[i] = binaryString.charCodeAt(i);
}
- const opts = {};
- if (contentType) opts["type"] = contentType;
- return new Blob([byteArray], opts);
+ const blobProps = {};
+ if (opts?.contentType) blobProps["type"] = opts.contentType;
+ return new Blob([byteArray], blobProps);
}
private isBase64(str: string): boolean {
@@ -89,14 +92,25 @@ class StorageClient {
}
}
- private async urlToBlob(url: string, contentType?: string): Promise<Blob> {
- const response = await fetch(url);
+ private async urlToBlob(url: string, opts?: imageOptions): Promise<Blob> {
+ let response: Response;
+ if (opts?.height && opts?.width) {
+ try {
+ response = await fetchWithTimeout(
+ `https://wsrv.nl/?w=${opts.width}&h=${opts.height}&fit=cover&url=${url}`,
+ );
+ } catch (error) {
+ response = await fetch(url);
+ }
+ } else {
+ response = await fetch(url);
+ }
if (!response.ok) {
throw new Error(`Failed to fetch URL: ${response.statusText}`);
}
const blob = await response.blob();
- if (contentType) {
- return new Blob([blob], { type: contentType });
+ if (opts?.contentType) {
+ return new Blob([blob], { type: opts.contentType });
}
return blob;
}
diff --git a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
index 1d2431adbb..e971c60a33 100644
--- a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
@@ -1,9 +1,11 @@
+import { resizeImage } from "@/lib/images";
import useProject from "@/lib/swr/use-project";
import { LinkProps } from "@/lib/types";
import { UploadCloud } from "@/ui/shared/icons";
import {
InfoTooltip,
LoadingCircle,
+ LoadingSpinner,
Popover,
SimpleTooltipContent,
Switch,
@@ -14,13 +16,7 @@ import { TooltipContent } from "@dub/ui/src/tooltip";
import { FADE_IN_ANIMATION_SETTINGS, HOME_DOMAIN } from "@dub/utils";
import { motion } from "framer-motion";
import { Link2 } from "lucide-react";
-import {
- Dispatch,
- SetStateAction,
- useCallback,
- useEffect,
- useState,
-} from "react";
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
import TextareaAutosize from "react-textarea-autosize";
import UnsplashSearch from "./unsplash-search";
@@ -40,29 +36,20 @@ export default function OGSection({
const { title, description, image, proxy } = data;
- const [fileError, setFileError] = useState<string | null>(null);
+ const [resizing, setResizing] = useState(false);
const [dragActive, setDragActive] = useState(false);
- const onChangePicture = useCallback(
- (e) => {
- setFileError(null);
- const file = e.target.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 5) {
- setFileError("File size too big (max 5MB)");
- } else if (file.type !== "image/png" && file.type !== "image/jpeg") {
- setFileError("File type not supported (.png or .jpg only)");
- } else {
- const reader = new FileReader();
- reader.onload = (e) => {
- setData((prev) => ({ ...prev, image: e.target?.result as string }));
- };
- reader.readAsDataURL(file);
- }
- }
- },
- [setData],
- );
+ const onChangePicture = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files && e.target.files[0];
+ if (!file) return;
+ setResizing(true);
+ const image = await resizeImage(file);
+ setData((prev) => ({ ...prev, image }));
+ // delay to prevent flickering
+ setTimeout(() => {
+ setResizing(false);
+ }, 500);
+ };
useEffect(() => {
if (proxy && props) {
@@ -143,44 +130,40 @@ export default function OGSection({
<div>
<div className="flex items-center justify-between">
<p className="block text-sm font-medium text-gray-700">Image</p>
- {fileError ? (
- <p className="text-sm text-red-500">{fileError}</p>
- ) : (
- <div className="flex items-center justify-between">
- <button
- className="mr-1 flex h-6 w-6 items-center justify-center rounded-md transition-colors duration-75 hover:bg-gray-100 active:bg-gray-200"
- type="button"
- onClick={() => {
- const image = window.prompt(
- "Paste a URL to an image (max 5MB)",
- "https://",
- );
- if (image) {
- setData((prev) => ({ ...prev, image }));
- }
- }}
- >
- <Link2 className="h-4 w-4 text-gray-500" />
- </button>
- <Popover
- content={
- <UnsplashSearch
- setData={setData}
- setOpenPopover={handleSet}
- />
+ <div className="flex items-center justify-between">
+ <button
+ className="mr-1 flex h-6 w-6 items-center justify-center rounded-md transition-colors duration-75 hover:bg-gray-100 active:bg-gray-200"
+ type="button"
+ onClick={() => {
+ const image = window.prompt(
+ "Paste a URL to an image.",
+ "https://",
+ );
+ if (image) {
+ setData((prev) => ({ ...prev, image }));
}
- openPopover={openPopover}
- setOpenPopover={handleSet}
+ }}
+ >
+ <Link2 className="h-4 w-4 text-gray-500" />
+ </button>
+ <Popover
+ content={
+ <UnsplashSearch
+ setData={setData}
+ setOpenPopover={handleSet}
+ />
+ }
+ openPopover={openPopover}
+ setOpenPopover={handleSet}
+ >
+ <div
+ onClick={handleSet}
+ className="flex h-6 w-6 cursor-pointer items-center justify-center rounded-md transition-colors duration-75 hover:bg-gray-100 active:bg-gray-200"
>
- <div
- onClick={handleSet}
- className="flex h-6 w-6 cursor-pointer items-center justify-center rounded-md transition-colors duration-75 hover:bg-gray-100 active:bg-gray-200"
- >
- <Unsplash className="h-3 w-3 text-gray-500" />
- </div>
- </Popover>
- </div>
- )}
+ <Unsplash className="h-3 w-3 text-gray-500" />
+ </div>
+ </Popover>
+ </div>
</div>
<label
htmlFor="image"
@@ -208,33 +191,19 @@ export default function OGSection({
e.stopPropagation();
setDragActive(false);
}}
- onDrop={(e) => {
+ onDrop={async (e) => {
e.preventDefault();
e.stopPropagation();
setDragActive(false);
- setFileError(null);
const file = e.dataTransfer.files && e.dataTransfer.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 5) {
- setFileError("File size too big (max 5MB)");
- } else if (
- file.type !== "image/png" &&
- file.type !== "image/jpeg"
- ) {
- setFileError(
- "File type not supported (.png or .jpg only)",
- );
- } else {
- const reader = new FileReader();
- reader.onload = (e) => {
- setData((prev) => ({
- ...prev,
- image: e.target?.result as string,
- }));
- };
- reader.readAsDataURL(file);
- }
- }
+ if (!file) return;
+ setResizing(true);
+ const image = await resizeImage(file);
+ setData((prev) => ({ ...prev, image }));
+ // delay to prevent flickering
+ setTimeout(() => {
+ setResizing(false);
+ }, 500);
}}
/>
<div
@@ -248,17 +217,28 @@ export default function OGSection({
: "group-hover:bg-gray-50"
}`}
>
- <UploadCloud
- className={`${
- dragActive ? "scale-110" : "scale-100"
- } h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
- />
- <p className="mt-2 text-center text-sm text-gray-500">
- Drag and drop or click to upload.
- </p>
- <p className="mt-2 text-center text-sm text-gray-500">
- Recommended: 1200 x 630 pixels (max 5MB)
- </p>
+ {resizing ? (
+ <>
+ <LoadingSpinner />
+ <p className="mt-2 text-center text-sm text-gray-500">
+ Resizing image...
+ </p>
+ </>
+ ) : (
+ <>
+ <UploadCloud
+ className={`${
+ dragActive ? "scale-110" : "scale-100"
+ } h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
+ />
+ <p className="mt-2 text-center text-sm text-gray-500">
+ Drag and drop or click to upload.
+ </p>
+ <p className="mt-2 text-center text-sm text-gray-500">
+ Recommended: 1200 x 630 pixels
+ </p>
+ </>
+ )}
<span className="sr-only">OG image upload</span>
</div>
{image && (
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ddb6fc0c10..7f7018a8ee 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -13158,7 +13158,7 @@ packages:
optional: true
dependencies:
prettier: 3.2.5
- prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
+ prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
dev: true