From ca54e3f819fad009ac3c3c8b57a26014a2652a73 Mon Sep 17 00:00:00 2001
From: Gabriel Pereira Woitechen <wtchnm@icloud.com>
Date: Wed, 4 Sep 2024 10:32:03 -0300
Subject: [PATCH] perf(astro/assets): avoid downloading original image when
 using cache (#11904)

---
 .changeset/purple-ears-sneeze.md            |  5 +++++
 packages/astro/src/assets/build/generate.ts | 17 ++++++++---------
 2 files changed, 13 insertions(+), 9 deletions(-)
 create mode 100644 .changeset/purple-ears-sneeze.md

diff --git a/.changeset/purple-ears-sneeze.md b/.changeset/purple-ears-sneeze.md
new file mode 100644
index 0000000000..b79cc2e68b
--- /dev/null
+++ b/.changeset/purple-ears-sneeze.md
@@ -0,0 +1,5 @@
+---
+'astro': patch
+---
+
+perf(assets): avoid downloading original image when using cache
diff --git a/packages/astro/src/assets/build/generate.ts b/packages/astro/src/assets/build/generate.ts
index fcc19f4f53..645a0acdcb 100644
--- a/packages/astro/src/assets/build/generate.ts
+++ b/packages/astro/src/assets/build/generate.ts
@@ -98,11 +98,11 @@ export async function generateImagesForPath(
 	env: AssetEnv,
 	queue: PQueue,
 ) {
-	const originalImageData = await loadImage(originalFilePath, env);
+	let originalImage: ImageData;
 
 	for (const [_, transform] of transformsAndPath.transforms) {
 		await queue
-			.add(async () => generateImage(originalImageData, transform.finalPath, transform.transform))
+			.add(async () => generateImage(transform.finalPath, transform.transform))
 			.catch((e) => {
 				throw e;
 			});
@@ -128,13 +128,9 @@ export async function generateImagesForPath(
 		}
 	}
 
-	async function generateImage(
-		originalImage: ImageData,
-		filepath: string,
-		options: ImageTransform,
-	) {
+	async function generateImage(filepath: string, options: ImageTransform) {
 		const timeStart = performance.now();
-		const generationData = await generateImageInternal(originalImage, filepath, options);
+		const generationData = await generateImageInternal(filepath, options);
 
 		const timeEnd = performance.now();
 		const timeChange = getTimeStat(timeStart, timeEnd);
@@ -151,7 +147,6 @@ export async function generateImagesForPath(
 	}
 
 	async function generateImageInternal(
-		originalImage: ImageData,
 		filepath: string,
 		options: ImageTransform,
 	): Promise<GenerationData> {
@@ -207,6 +202,10 @@ export async function generateImagesForPath(
 			? (options.src as ImageMetadata).src
 			: (options.src as string);
 
+		if (!originalImage) {
+			originalImage = await loadImage(originalFilePath, env);
+		}
+
 		let resultData: Partial<ImageData> = {
 			data: undefined,
 			expires: originalImage.expires,