Skip to content

Commit 106e7b5

Browse files
fix: wait for approximate minimum bytes before probing for dimensions
1 parent 3c71ca8 commit 106e7b5

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

utils/get-image-dimensions.js

+25-4
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,47 @@ const errorLogger = require('./error-logger');
44
const { getCache, setCache } = require('./cache');
55
const defaultDimensions = { width: 600, height: 400 };
66

7+
// Minimum required bytes for common image formats (approximate)
8+
const imageMinBytes = {
9+
jpg: 410,
10+
png: 33,
11+
gif: 14,
12+
webp: 30,
13+
bmp: 26,
14+
default: 256 // Fallback for other image types
15+
};
16+
717
const probeImage = async url => {
818
const response = await fetch(url);
919
if (!response.ok)
1020
throw new Error(`Failed to fetch image: ${response.statusText}`);
1121

1222
const chunks = [];
23+
let totalLength = 0;
1324
const reader = response.body;
1425

1526
for await (const chunk of reader) {
1627
chunks.push(chunk);
28+
totalLength += chunk.length;
1729

1830
try {
19-
// Try to determine image size with available data
20-
const dimensions = imageSize(Buffer.concat(chunks));
31+
const buffer = Buffer.concat(chunks, totalLength);
32+
33+
// Try to detect image format (first few bytes)
34+
const { type } = imageSize(buffer);
35+
const minBytes = imageMinBytes[type] || imageMinBytes.default;
36+
37+
// Check buffer length before probing image
38+
if (buffer.length < minBytes) continue;
39+
40+
// Get dimensions
41+
const dimensions = imageSize(buffer);
2142
if (dimensions.width && dimensions.height) {
22-
response.body.destroy(); // Stop data stream
43+
response.body.destroy(); // Stop downloading
2344
return dimensions;
2445
}
2546
} catch (err) {
26-
// Keep reading if more data is needed
47+
// Continue reading if more data is needed
2748
}
2849
}
2950

0 commit comments

Comments
 (0)