Skip to content

AI-native design editor. Open-source Figma alternative.

refactor: read image types and sizes with image-size (#1489)

Danila Poyarkov16e64fe0ba4f
diff --git a/bun.lock b/bun.lock
index 8d71a4b46..0112e86fa 100644
--- a/bun.lock
+++ b/bun.lock
@@ -415,6 +415,7 @@
"dependencies": {
"@xmldom/xmldom": "^0.9.12",
"fflate": "^0.8.3",
+ "image-size": "^2.0.4",
"js-base64": "^3.9.3",
},
"devDependencies": {
@@ -560,6 +561,7 @@
"@noble/hashes": "^2.4.0",
"culori": "^4.0.2",
"es-toolkit": "^1.52.0",
+ "image-size": "^2.0.4",
"nanoevents": "^9.1.0",
"postcss-value-parser": "^4.2.0",
"svgpath": "^2.6.0",
@@ -3510,7 +3512,7 @@
"ignore": ["[email protected]", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
- "image-size": ["[email protected]", "", { "dependencies": { "queue": "6.0.2" }, "bin": { "image-size": "bin/image-size.js" } }, "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw=="],
+ "image-size": ["[email protected]", "", { "bin": { "image-size": "bin/image-size.js" } }, "sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw=="],
"immediate": ["[email protected]", "", {}, "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="],
@@ -5510,6 +5512,8 @@
"pptxgenjs/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],
+ "pptxgenjs/image-size": ["[email protected]", "", { "dependencies": { "queue": "6.0.2" }, "bin": { "image-size": "bin/image-size.js" } }, "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw=="],
+
"prebuild-install/tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw=="],
"precinct/commander": ["[email protected]", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
@@ -5578,8 +5582,6 @@
"sucrase/commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],
- "svgdom/image-size": ["[email protected]", "", { "bin": { "image-size": "bin/image-size.js" } }, "sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw=="],
-
"tempy/is-stream": ["[email protected]", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"tempy/type-fest": ["[email protected]", "", {}, "sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg=="],
diff --git a/packages/core/src/editor/clipboard/assets.ts b/packages/core/src/editor/clipboard/assets.ts
index a10d338e5..5c2be5c95 100644
--- a/packages/core/src/editor/clipboard/assets.ts
+++ b/packages/core/src/editor/clipboard/assets.ts
@@ -2,7 +2,11 @@ import { sumBy } from 'es-toolkit'
import type { Fill } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
-import { computeImageHash } from '@open-pencil/scene-graph/images'
+import {
+ computeImageHash,
+ IMPORTABLE_RASTER_TYPES,
+ isSVGFile
+} from '@open-pencil/scene-graph/images'
import Matrix from '@open-pencil/scene-graph/matrix'
import { TRANSPARENT } from '#core/constants'
@@ -20,14 +24,6 @@ import { computeAllLayouts } from '#core/layout'
const IMAGE_MAX_DIMENSION = 4096
const ASSET_GAP = 20
-const RASTER_IMAGE_TYPES = new Set([
- 'image/png',
- 'image/jpeg',
- 'image/webp',
- 'image/gif',
- 'image/avif'
-])
-
interface PreparedRasterAsset {
kind: 'raster'
bytes: Uint8Array
@@ -53,12 +49,6 @@ type PushCreatedNodesUndo = (
label?: string
) => void
-function isSVGFile(file: Pick<File, 'name' | 'type'>): boolean {
- return (
- file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))
- )
-}
-
export function createClipboardAssetActions(
ctx: EditorContext,
pushCreatedNodesUndo: PushCreatedNodesUndo
@@ -98,7 +88,7 @@ export function createClipboardAssetActions(
}
: null
}
- if (!RASTER_IMAGE_TYPES.has(file.type)) return null
+ if (!IMPORTABLE_RASTER_TYPES.has(file.type)) return null
const bytes = new Uint8Array(await file.arrayBuffer())
const dimensions = decodeImageDimensions(bytes)
return dimensions ? { kind: 'raster', bytes, name: file.name, ...dimensions } : null
@@ -203,7 +193,7 @@ export function createClipboardAssetActions(
function placeImageFiles(files: File[], cx: number, cy: number) {
return placeFiles(
- files.filter((file) => RASTER_IMAGE_TYPES.has(file.type)),
+ files.filter((file) => IMPORTABLE_RASTER_TYPES.has(file.type)),
cx,
cy
)
diff --git a/packages/core/src/figma-api/images.ts b/packages/core/src/figma-api/images.ts
index 779b77c92..d9415af6f 100644
--- a/packages/core/src/figma-api/images.ts
+++ b/packages/core/src/figma-api/images.ts
@@ -3,7 +3,7 @@
import type { SceneGraph } from '@open-pencil/scene-graph'
import {
computeImageHash,
- imageMimeType,
+ imageHeader,
imageSize,
type ImageMimeType
} from '@open-pencil/scene-graph/images'
@@ -19,30 +19,19 @@ const MAX_IMAGE_SIDE = 4096
/** The most bytes `createImageAsync` reads from a response, well above any 4096 × 4096 image. */
export const MAX_IMAGE_FETCH_BYTES = 64 * 1024 * 1024
-/**
- * The bytes Figma needs before it takes an image: a PNG's header through its bit depth and color
- * type, and a GIF's logical screen size. A JPEG needs its start-of-frame, which `imageSize` reads.
- */
-const MIN_HEADER_BYTES: Partial<Record<ImageMimeType, number>> = {
- 'image/png': 26,
- 'image/gif': 10
-}
-
-/** A PNG's signature and the type of its first chunk, which Figma requires byte for byte. */
-const PNG_HEADER = [
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52
-]
+/** The formats Figma's `createImage` takes; it refuses WebP, SVG, and the rest. */
+const FIGMA_IMAGE_TYPES: ReadonlySet<ImageMimeType> = new Set([
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif'
+])
/** Figma's complaint about `data` as an image, or null when it takes it. */
function imageProblem(data: Uint8Array): string | null {
- const type = imageMimeType(data)
- const size = type === 'image/webp' ? null : imageSize(data)
- if (!size || size.width === 0 || size.height === 0) return 'Image type is unsupported'
- if (type === 'image/png' && PNG_HEADER.some((byte, index) => data[index] !== byte)) {
- return 'Image type is unsupported'
- }
- if (data.length < (MIN_HEADER_BYTES[type] ?? 0)) return 'Image type is unsupported'
- if (size.width > MAX_IMAGE_SIDE || size.height > MAX_IMAGE_SIDE) return 'Image is too large'
+ const header = imageHeader(data)
+ if (!header || !FIGMA_IMAGE_TYPES.has(header.type)) return 'Image type is unsupported'
+ if (header.width === 0 || header.height === 0) return 'Image type is unsupported'
+ if (header.width > MAX_IMAGE_SIDE || header.height > MAX_IMAGE_SIDE) return 'Image is too large'
return null
}
diff --git a/packages/core/tests/figma-api/images.test.ts b/packages/core/tests/figma-api/images.test.ts
index 62f44e344..17bf0d0a8 100644
--- a/packages/core/tests/figma-api/images.test.ts
+++ b/packages/core/tests/figma-api/images.test.ts
@@ -89,8 +89,8 @@ describe('figma.createImage', () => {
})
test('takes a PNG, JPEG, or GIF up to 4096 pixels a side, and finds only images it stored', async () => {
- const png = (width: number, height: number, length = 26) =>
- `new Uint8Array(${JSON.stringify(pngHeader(width, height).slice(0, length))})`
+ const png = (width: number, height: number) =>
+ `new Uint8Array(${JSON.stringify(pngHeader(width, height))})`
/** A 1 × 1 PNG header with `value` at `index`, breaking its signature or chunk type. */
const brokenPNG = (index: number, value: number) =>
`(() => { const bytes = ${png(1, 1)}; bytes[${index}] = ${value}; return figma.createImage(bytes).hash })()`
@@ -101,8 +101,6 @@ describe('figma.createImage', () => {
wide: `figma.createImage(${png(4097, 1)}).hash`,
tall: `figma.createImage(${png(1, 4097)}).hash`,
empty: `figma.createImage(${png(0, 0)}).hash`,
- noColorType: `figma.createImage(${png(1, 1, 25)}).hash`,
- signature: brokenPNG(0, 0),
lineEnding: brokenPNG(4, 0),
chunkType: brokenPNG(12, 0x58),
webp: `figma.createImage(bytes('${WEBP_1X1}')).hash`,
@@ -118,8 +116,6 @@ describe('figma.createImage', () => {
wide: 'in createImage: Image is too large',
tall: 'in createImage: Image is too large',
empty: 'in createImage: Image type is unsupported',
- noColorType: 'in createImage: Image type is unsupported',
- signature: 'in createImage: Image type is unsupported',
lineEnding: 'in createImage: Image type is unsupported',
chunkType: 'in createImage: Image type is unsupported',
webp: 'in createImage: Image type is unsupported',
diff --git a/packages/core/tests/io/formats/fig/export/meta.test.ts b/packages/core/tests/io/formats/fig/export/meta.test.ts
index f27118f42..eb4dc6b98 100644
--- a/packages/core/tests/io/formats/fig/export/meta.test.ts
+++ b/packages/core/tests/io/formats/fig/export/meta.test.ts
@@ -7,8 +7,9 @@ import * as v from 'valibot'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
-import { parseFigBuffer, pngSize, readFigArchiveMeta } from '@open-pencil/fig'
+import { parseFigBuffer, readFigArchiveMeta } from '@open-pencil/fig'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { imageSize } from '@open-pencil/scene-graph/images'
setDefaultTimeout(60_000)
@@ -34,7 +35,7 @@ function readArchive(bytes: Uint8Array) {
return {
raw,
meta: meta.output,
- thumbnailSize: expectDefined(pngSize(png), 'thumbnail size')
+ thumbnailSize: expectDefined(imageSize(png), 'thumbnail size')
}
}
diff --git a/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts b/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts
index 25c312a0b..13d675b9a 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts
@@ -8,12 +8,12 @@ import { heavy } from '#core-tests/helpers/test-utils'
import { unzipSync } from 'fflate'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
-import { pngSize } from '@open-pencil/fig'
import { isZstdCompressed } from '@open-pencil/kiwi/fig'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { parseFigKiwiChunks } from '@open-pencil/kiwi/fig/container'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
+import { imageSize } from '@open-pencil/scene-graph/images'
import {
type Mismatch,
@@ -472,7 +472,7 @@ function verifyFixture(spec: FixtureSpec): void {
await g0Ready
const thumb = g0Zip['thumbnail.png']
expect(thumb.byteLength).toBe(spec.thumbnailSize)
- expect(pngSize(thumb)).toEqual({ width: spec.thumbnailWidth, height: spec.thumbnailHeight })
+ expect(imageSize(thumb)).toEqual({ width: spec.thumbnailWidth, height: spec.thumbnailHeight })
})
test('original fig-kiwi container', async () => {
diff --git a/packages/dom-css/tests/export/shaders.test.ts b/packages/dom-css/tests/export/shaders.test.ts
index e8e68e178..9e9552dd5 100644
--- a/packages/dom-css/tests/export/shaders.test.ts
+++ b/packages/dom-css/tests/export/shaders.test.ts
@@ -11,7 +11,11 @@ const PRESET = {
components: [{ type: 'Aurora', props: { colorA: '#ff3300', speed: 2 } }, { type: 'FilmGrain' }]
}
const FRAME = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
-const JPEG_FRAME = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 16, 74, 70, 73, 70])
+/** A JPEG's header through its frame, which declares a 37 × 21 image. */
+const JPEG_FRAME = new Uint8Array([
+ 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc4, 0x00, 0x02, 0xff, 0xc0, 0x00, 0x11,
+ 0x08, 0x00, 0x15, 0x00, 0x25, 0x03
+])
/** A layer with no children that fills with a shader, whose still frame is saved. */
function shaderLayer(frame = FRAME) {
diff --git a/packages/drawio/package.json b/packages/drawio/package.json
index 2f43c91f7..1df142b87 100644
--- a/packages/drawio/package.json
+++ b/packages/drawio/package.json
@@ -37,6 +37,7 @@
"dependencies": {
"@xmldom/xmldom": "^0.9.12",
"fflate": "^0.8.3",
+ "image-size": "^2.0.4",
"js-base64": "^3.9.3"
},
"devDependencies": {
diff --git a/packages/drawio/src/embedded.ts b/packages/drawio/src/embedded.ts
index afbc5e6e1..c50b25a80 100644
--- a/packages/drawio/src/embedded.ts
+++ b/packages/drawio/src/embedded.ts
@@ -1,9 +1,11 @@
import type { Element } from '@xmldom/xmldom'
+import { imageSize } from 'image-size'
import { boundedInflate, percentDecoded, type InflateBudget } from './inflate'
import { parseXML } from './xml'
-const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
+/** A PNG's chunks start after its eight-byte signature. */
+const PNG_SIGNATURE_LENGTH = 8
/** The keyword draw.io stores its diagram under in a PNG's text chunks. */
const DRAWIO_KEYWORD = 'mxfile'
@@ -11,7 +13,11 @@ const latin1 = new TextDecoder('latin1')
const utf8 = new TextDecoder()
function isPNG(bytes: Uint8Array): boolean {
- return PNG_SIGNATURE.every((byte, index) => bytes[index] === byte)
+ try {
+ return imageSize(bytes).type === 'png'
+ } catch {
+ return false
+ }
}
/** Where a NUL byte ends the field that starts at `from`, or -1. */
@@ -48,7 +54,7 @@ function chunkDiagram(type: string, data: Uint8Array, budget: InflateBudget): st
*/
function diagramInPNG(bytes: Uint8Array, budget: InflateBudget): string | null {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
- let offset = PNG_SIGNATURE.length
+ let offset = PNG_SIGNATURE_LENGTH
while (offset + 8 <= bytes.length) {
const length = view.getUint32(offset)
const type = latin1.decode(bytes.subarray(offset + 4, offset + 8))
diff --git a/packages/drawio/tests/read.test.ts b/packages/drawio/tests/read.test.ts
index adbc9fe15..21d83b5f8 100644
--- a/packages/drawio/tests/read.test.ts
+++ b/packages/drawio/tests/read.test.ts
@@ -143,10 +143,12 @@ function chunk(type: string, data: Uint8Array): Uint8Array {
return out
}
-/** A PNG holding only the given chunks between its signature and `IEND`. */
+/** A 1 × 1 PNG holding the given chunks between its `IHDR` and `IEND`. */
function png(...chunks: Uint8Array[]): Uint8Array {
const signature = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
- return concat([signature, ...chunks, chunk('IEND', new Uint8Array())])
+ // Width and height 1, bit depth 8, color type 6 (RGBA), default compression, filter, interlace.
+ const header = Uint8Array.from([0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0])
+ return concat([signature, chunk('IHDR', header), ...chunks, chunk('IEND', new Uint8Array())])
}
/** A PNG holding only the chunk draw.io adds: a `tEXt` chunk under `keyword`. */
@@ -196,7 +198,8 @@ describe('reading the diagram a draw.io export embeds', () => {
'Could not read the draw.io diagram in this image'
)
const whole = pngWithText('mxfile', `<mxfile>${page('Embedded')}</mxfile>`)
- expect(() => readDrawIOBytes(whole.subarray(0, 40))).toThrow('cut short')
+ // Dropping `IEND`, the text chunk's CRC, and a few bytes of its data.
+ expect(() => readDrawIOBytes(whole.subarray(0, -20))).toThrow('cut short')
})
test('takes an SVG’s comments before its root in stride', () => {
diff --git a/packages/fig/src/archive.ts b/packages/fig/src/archive.ts
index e7d8e0d30..90c422cfb 100644
--- a/packages/fig/src/archive.ts
+++ b/packages/fig/src/archive.ts
@@ -13,7 +13,7 @@ import type { HeaderFields } from '@open-pencil/kiwi/schema-runtime'
import type { Color, Rect, Size } from '@open-pencil/scene-graph/primitives'
import { figArchiveMetaSchema, type FigArchiveMetaJSON } from './schema'
-import { hasPNGSignature } from './thumbnail'
+import { isPNG } from './thumbnail'
export interface FigImageEntry {
name: string
@@ -72,7 +72,7 @@ function parseRawFigKiwi(
if (!chunks) return null
const decoded = decodeFigKiwiCanvas(bytes, onPages, headers)
- const thumbnailPNG = chunks.slice(2).find(hasPNGSignature) ?? null
+ const thumbnailPNG = chunks.slice(2).find(isPNG) ?? null
return { ...decoded, images: [], thumbnailPNG, metaJSON: null }
}
@@ -145,7 +145,7 @@ export function readFigArchiveParts(buffer: ArrayBuffer): FigArchiveParts {
const bytes = new Uint8Array(buffer)
const chunks = parseFigKiwiChunks(bytes)
if (chunks) {
- const thumbnailPNG = chunks.slice(2).find(hasPNGSignature) ?? null
+ const thumbnailPNG = chunks.slice(2).find(isPNG) ?? null
return { ...canvasParts(bytes), images: [], thumbnailPNG, metaJSON: null }
}
const canvasArchive = unzipSync(bytes, { filter: ({ name }) => isCanonicalCanvasEntry(name) })
diff --git a/packages/fig/src/index.ts b/packages/fig/src/index.ts
index c39142028..17353300a 100644
--- a/packages/fig/src/index.ts
+++ b/packages/fig/src/index.ts
@@ -37,7 +37,6 @@ export {
} from './record-patch'
export {
extractFigThumbnailFromReader,
- pngSize,
type FigRangeReader,
type FigThumbnailLimits
} from './thumbnail'
diff --git a/packages/fig/src/thumbnail.ts b/packages/fig/src/thumbnail.ts
index 9bfb17b56..fa7a35b00 100644
--- a/packages/fig/src/thumbnail.ts
+++ b/packages/fig/src/thumbnail.ts
@@ -1,6 +1,6 @@
import { inflateSync } from 'fflate'
-import type { Size } from '@open-pencil/scene-graph/primitives'
+import { imageHeader } from '@open-pencil/scene-graph/images'
export interface FigRangeReader {
readonly size: number
@@ -29,7 +29,6 @@ const DEFAULT_MAX_TAIL = 4 * 1024 * 1024
const DEFAULT_MAX_COMPRESSED = 8 * 1024 * 1024
const DEFAULT_MAX_OUTPUT = 16 * 1024 * 1024
const THUMBNAIL_NAME = 'thumbnail.png'
-const PNG_SIGNATURE = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
function view(bytes: Uint8Array): DataView {
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
@@ -47,20 +46,14 @@ function boundedLimit(value: number | undefined, fallback: number): number {
return Number.isFinite(value) && value && value > 0 ? value : fallback
}
-export function hasPNGSignature(bytes: Uint8Array): boolean {
- return PNG_SIGNATURE.every((byte, index) => bytes[index] === byte)
-}
-
-/** A PNG's size in pixels, read from its IHDR chunk; null for bytes that are not a PNG. */
-export function pngSize(bytes: Uint8Array): Size | null {
- if (bytes.byteLength < 24 || !hasPNGSignature(bytes)) return null
- const data = view(bytes)
- return { width: data.getUint32(16), height: data.getUint32(20) }
+/** Whether `bytes` hold a PNG, as a `.fig` thumbnail does. */
+export function isPNG(bytes: Uint8Array): boolean {
+ return imageHeader(bytes)?.type === 'image/png'
}
function hasUsablePNGDimensions(bytes: Uint8Array): boolean {
- const size = pngSize(bytes)
- return size !== null && size.width > 1 && size.height > 1
+ const header = imageHeader(bytes)
+ return header?.type === 'image/png' && header.width > 1 && header.height > 1
}
function findThumbnailEntry(
diff --git a/packages/fig/tests/index.test.ts b/packages/fig/tests/index.test.ts
index e57e27313..543f68fe8 100644
--- a/packages/fig/tests/index.test.ts
+++ b/packages/fig/tests/index.test.ts
@@ -12,6 +12,7 @@ import {
writeFigContainer
} from '#fig/index'
import { deflateSync } from 'fflate'
+import { toUint8Array } from 'js-base64'
import {
createNodeChangesMessage,
@@ -21,6 +22,9 @@ import {
} from '@open-pencil/kiwi/fig/codec'
const PNG_SIGNATURE = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
+/** A 3 × 2 PNG, as a `.fig` thumbnail chunk holds one. */
+const PNG_3X2 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAIAAAASFvFNAAAAEElEQVR4nGP4z8AAQQxwFgBB0gX7h/C5SAAAAABJRU5ErkJggg=='
function appendChunk(container: Uint8Array, chunk: Uint8Array): Uint8Array {
const bytes = new Uint8Array(container.byteLength + 4 + chunk.byteLength)
@@ -146,7 +150,7 @@ describe('@open-pencil/fig package API', () => {
},
{ version: 1 }
)
- const thumbnailPNG = new Uint8Array([...PNG_SIGNATURE, 1, 2, 3])
+ const thumbnailPNG = toUint8Array(PNG_3X2)
const bytes = appendChunk(container, thumbnailPNG)
const parsed = parseFigBuffer(bytes.buffer as ArrayBuffer)
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index 683b38202..c1008a5b1 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -390,6 +390,7 @@
"@noble/hashes": "^2.4.0",
"culori": "^4.0.2",
"es-toolkit": "^1.52.0",
+ "image-size": "^2.0.4",
"nanoevents": "^9.1.0",
"postcss-value-parser": "^4.2.0",
"svgpath": "^2.6.0",
diff --git a/packages/scene-graph/src/images.ts b/packages/scene-graph/src/images.ts
index 89d7824be..31d89a66c 100644
--- a/packages/scene-graph/src/images.ts
+++ b/packages/scene-graph/src/images.ts
@@ -1,5 +1,6 @@
import { sha1 } from '@noble/hashes/legacy.js'
import { bytesToHex } from '@noble/hashes/utils.js'
+import { imageSize as readImageHeader } from 'image-size'
import type { Matrix, Size } from './primitives'
@@ -14,63 +15,61 @@ export function computeImageHash(data: Uint8Array): string {
export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'
-/**
- * The media type of encoded image bytes, read from their signature, for writing them out as a
- * data URL or file. Bytes with no known signature are reported as PNG, as image fills began.
- */
-export function imageMimeType(data: Uint8Array): ImageMimeType {
- if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return 'image/jpeg'
- if (data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46) return 'image/gif'
- const riff = data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46
- const webp = data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50
- if (riff && webp) return 'image/webp'
- return 'image/png'
+/** The image types documents store, by the name `image-size` gives each format. */
+const IMAGE_MIME_TYPES: Partial<Record<string, ImageMimeType>> = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ gif: 'image/gif',
+ webp: 'image/webp'
}
-function jpegSize(data: Uint8Array, view: DataView): Size | null {
- for (let offset = 2; offset + 9 < data.length;) {
- if (data[offset] !== 0xff) return null
- const marker = data[offset + 1]
- const length = view.getUint16(offset + 2)
- // Start-of-frame markers, except the DHT, JPG, and DAC ones that share their range.
- if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
- return { width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) }
- }
- offset += 2 + length
- }
- return null
+/** The raster types a dropped or pasted file can be imported as an image fill from. */
+export const IMPORTABLE_RASTER_TYPES: ReadonlySet<string> = new Set([
+ 'image/png',
+ 'image/jpeg',
+ 'image/webp',
+ 'image/gif',
+ 'image/avif'
+])
+
+/** Whether a file is an SVG image, which some systems report without a media type. */
+export function isSVGFile(file: { name: string; type: string }): boolean {
+ return (
+ file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))
+ )
}
-function webpSize(data: Uint8Array, view: DataView): Size | null {
- const chunk = String.fromCharCode(data[12], data[13], data[14], data[15])
- if (chunk === 'VP8X' && data.length >= 30) {
- const width = 1 + (data[24] | (data[25] << 8) | (data[26] << 16))
- const height = 1 + (data[27] | (data[28] << 8) | (data[29] << 16))
- return { width, height }
- }
- if (chunk === 'VP8L' && data.length >= 25) {
- const bits = view.getUint32(21, true)
- return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }
- }
- if (chunk === 'VP8 ' && data.length >= 30) {
- return { width: view.getUint16(26, true) & 0x3fff, height: view.getUint16(28, true) & 0x3fff }
+export interface ImageHeader extends Size {
+ type: ImageMimeType
+}
+
+/**
+ * The type and size of a PNG, JPEG, GIF, or WebP, read from its header by `image-size`; null for
+ * bytes it cannot read and for other formats.
+ */
+export function imageHeader(data: Uint8Array): ImageHeader | null {
+ let header: ReturnType<typeof readImageHeader>
+ try {
+ header = readImageHeader(data)
+ } catch {
+ return null
}
- return null
+ const type = header.type === undefined ? undefined : IMAGE_MIME_TYPES[header.type]
+ return type ? { type, width: header.width, height: header.height } : null
+}
+
+/**
+ * The media type of encoded image bytes, read from their header, for writing them out as a data
+ * URL or file. Bytes it cannot read are reported as PNG, as image fills began.
+ */
+export function imageMimeType(data: Uint8Array): ImageMimeType {
+ return imageHeader(data)?.type ?? 'image/png'
}
/** An image's size in pixels, read from its header; null for bytes it cannot read. */
export function imageSize(data: Uint8Array): Size | null {
- const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
- const type = imageMimeType(data)
- if (type === 'image/jpeg') return jpegSize(data, view)
- if (type === 'image/gif') {
- return data.length >= 10
- ? { width: view.getUint16(6, true), height: view.getUint16(8, true) }
- : null
- }
- if (type === 'image/webp') return webpSize(data, view)
- const png = data.length >= 24 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47
- return png ? { width: view.getUint32(16), height: view.getUint32(20) } : null
+ const header = imageHeader(data)
+ return header && { width: header.width, height: header.height }
}
/**
diff --git a/packages/scene-graph/tests/images.test.ts b/packages/scene-graph/tests/images.test.ts
index 499765634..886f28765 100644
--- a/packages/scene-graph/tests/images.test.ts
+++ b/packages/scene-graph/tests/images.test.ts
@@ -5,8 +5,10 @@ import { toUint8Array } from 'js-base64'
import {
computeImageHash,
coverImageTransform,
+ imageHeader,
imageMimeType,
- imageSize
+ imageSize,
+ isSVGFile
} from '@open-pencil/scene-graph/images'
describe('computeImageHash', () => {
@@ -18,22 +20,6 @@ describe('computeImageHash', () => {
})
})
-describe('imageMimeType', () => {
- test('reads the type from the bytes', () => {
- expect(imageMimeType(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBe(
- 'image/png'
- )
- expect(imageMimeType(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]))).toBe('image/jpeg')
- expect(imageMimeType(new TextEncoder().encode('GIF89a'))).toBe('image/gif')
- expect(imageMimeType(new TextEncoder().encode('RIFF\0\0\0\0WEBPVP8 '))).toBe('image/webp')
- })
-
- test('reports bytes with no known signature as PNG', () => {
- expect(imageMimeType(new TextEncoder().encode('RIFF\0\0\0\0WAVEfmt '))).toBe('image/png')
- expect(imageMimeType(new Uint8Array())).toBe('image/png')
- })
-})
-
describe('coverImageTransform', () => {
test('crops the image to cover the layer, centred, as Figma starts a crop', () => {
// Measured in Figma: a 412 × 364 image cropped on a 160 × 120 layer.
@@ -49,26 +35,82 @@ describe('coverImageTransform', () => {
})
})
-describe('imageSize', () => {
- // 37 × 21 images, encoded by Pillow.
- test.each([
- ['PNG', 'iVBORw0KGgoAAAANSUhEUgAAACUAAAAVCAIAAABOhrD5AAAANklEQVR4nO3NMREAAAzCQIp/z60EllwnXkAyq1f+3ak/luFe0h/LcC/pj2W4l/THMtxL+hPqAPB4ASnUWyUUAAAAAElFTkSuQmCC'],
- ['GIF', 'R0lGODdhJQAVAIEAAP8AAAAAAAAAAAAAACwAAAAAJQAVAEAILwABCBxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjyBDihxJsqRJkgEBADs='],
- ['lossless WebP', 'UklGRhwAAABXRUJQVlA4TA8AAAAvJAAFAAcQ/Y/+ByKi/wEA'],
- ['lossy WebP', 'UklGRk4AAABXRUJQVlA4IEIAAACQAwCdASolABUAPm02l0ikIyIhJWgAgA2JZwDPkoB+AAAr98NwAP7wm0P/5BcsLrka//yA/5Af8gP/498Ql180AAA=']
- ])('reads a %s header', (_format, base64) => {
- expect(imageSize(toUint8Array(base64))).toEqual({ width: 37, height: 21 })
+// 37 × 21 images, encoded by Pillow.
+const IMAGES = [
+ [
+ 'PNG',
+ 'image/png',
+ 'iVBORw0KGgoAAAANSUhEUgAAACUAAAAVCAIAAABOhrD5AAAANklEQVR4nO3NMREAAAzCQIp/z60EllwnXkAyq1f+3ak/luFe0h/LcC/pj2W4l/THMtxL+hPqAPB4ASnUWyUUAAAAAElFTkSuQmCC'
+ ],
+ [
+ 'GIF',
+ 'image/gif',
+ 'R0lGODdhJQAVAIEAAP8AAAAAAAAAAAAAACwAAAAAJQAVAEAILwABCBxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjyBDihxJsqRJkgEBADs='
+ ],
+ ['lossless WebP', 'image/webp', 'UklGRhwAAABXRUJQVlA4TA8AAAAvJAAFAAcQ/Y/+ByKi/wEA'],
+ [
+ 'lossy WebP',
+ 'image/webp',
+ 'UklGRk4AAABXRUJQVlA4IEIAAACQAwCdASolABUAPm02l0ikIyIhJWgAgA2JZwDPkoB+AAAr98NwAP7wm0P/5BcsLrka//yA/5Af8gP/498Ql180AAA='
+ ]
+] as const
+
+/** A JPEG whose frame header, declaring 37 × 21, follows a segment before it. */
+const JPEG = new Uint8Array([
+ 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc4, 0x00, 0x02, 0xff, 0xc0, 0x00, 0x11,
+ 0x08, 0x00, 0x15, 0x00, 0x25, 0x03
+])
+
+describe('imageHeader', () => {
+ test.each(IMAGES)('reads a %s header', (_format, type, base64) => {
+ expect(imageHeader(toUint8Array(base64))).toEqual({ type, width: 37, height: 21 })
})
test('reads a JPEG frame header past the segments before it', () => {
- const jpeg = new Uint8Array([
- 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc4, 0x00, 0x02, 0xff, 0xc0, 0x00,
- 0x11, 0x08, 0x00, 0x15, 0x00, 0x25, 0x03
- ])
- expect(imageSize(jpeg)).toEqual({ width: 37, height: 21 })
+ expect(imageHeader(JPEG)).toEqual({ type: 'image/jpeg', width: 37, height: 21 })
+ })
+
+ test('gives null for bytes it cannot read and for formats documents do not store', () => {
+ const svg = new TextEncoder().encode(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"/>'
+ )
+ const signatureOnly = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
+ for (const bytes of [
+ new TextEncoder().encode('not an image'),
+ new Uint8Array(),
+ svg,
+ signatureOnly
+ ]) {
+ expect(imageHeader(bytes)).toBeNull()
+ }
+ })
+})
+
+describe('imageMimeType', () => {
+ test('reads the type from the header', () => {
+ expect(IMAGES.map(([, , base64]) => imageMimeType(toUint8Array(base64)))).toEqual(
+ IMAGES.map(([, type]) => type)
+ )
+ expect(imageMimeType(JPEG)).toBe('image/jpeg')
})
- test('gives null for bytes it cannot read', () => {
+ test('reports bytes it cannot read as PNG', () => {
+ expect(imageMimeType(new TextEncoder().encode('RIFF\0\0\0\0WAVEfmt '))).toBe('image/png')
+ expect(imageMimeType(new Uint8Array())).toBe('image/png')
+ })
+})
+
+describe('imageSize', () => {
+ test('gives the size from the header, or null for bytes it cannot read', () => {
+ expect(imageSize(toUint8Array(IMAGES[0][2]))).toEqual({ width: 37, height: 21 })
expect(imageSize(new TextEncoder().encode('not an image'))).toBeNull()
})
})
+
+describe('isSVGFile', () => {
+ test('takes the SVG media type, or an .svg name when the system gives no type', () => {
+ expect(isSVGFile({ name: 'icon', type: 'image/svg+xml' })).toBe(true)
+ expect(isSVGFile({ name: 'Icon.SVG', type: '' })).toBe(true)
+ expect(isSVGFile({ name: 'icon.svg', type: 'image/png' })).toBe(false)
+ })
+})
diff --git a/packages/vue/src/canvas/drop/use.ts b/packages/vue/src/canvas/drop/use.ts
index 7adb902c2..5016b5885 100644
--- a/packages/vue/src/canvas/drop/use.ts
+++ b/packages/vue/src/canvas/drop/use.ts
@@ -2,16 +2,10 @@ import { useEventListener } from '@vueuse/core'
import { ref, type Ref } from 'vue'
import type { Editor } from '@open-pencil/core'
+import { IMPORTABLE_RASTER_TYPES, isSVGFile } from '@open-pencil/scene-graph/images'
import { cycleSafeTarget, findMoveDropTarget } from '#vue/shared/input/drop-target'
-const RASTER_IMAGE_TYPES = new Set([
- 'image/png',
- 'image/jpeg',
- 'image/webp',
- 'image/gif',
- 'image/avif'
-])
const COMPONENT_MIME = 'application/x-openpencil-component'
function hasComponentData(e: DragEvent): boolean {
@@ -99,18 +93,14 @@ function hasFileData(e: DragEvent): boolean {
return e.dataTransfer?.types.includes('Files') ?? false
}
-function isSVGFile(file: File): boolean {
- return (
- file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))
- )
-}
-
export function filterCanvasFiles(files: ArrayLike<File> | Iterable<File> | null): File[] {
if (!files) return []
- return Array.from(files).filter((file) => RASTER_IMAGE_TYPES.has(file.type) || isSVGFile(file))
+ return Array.from(files).filter(
+ (file) => IMPORTABLE_RASTER_TYPES.has(file.type) || isSVGFile(file)
+ )
}
export function extractImageFilesFromClipboard(e: ClipboardEvent): File[] {
const files = e.clipboardData?.files
- return files ? Array.from(files).filter((file) => RASTER_IMAGE_TYPES.has(file.type)) : []
+ return files ? Array.from(files).filter((file) => IMPORTABLE_RASTER_TYPES.has(file.type)) : []
}
diff --git a/src/app/ai/attachment/image/prepare.ts b/src/app/ai/attachment/image/prepare.ts
index c7bbdbbcc..815677a8c 100644
--- a/src/app/ai/attachment/image/prepare.ts
+++ b/src/app/ai/attachment/image/prepare.ts
@@ -1,3 +1,5 @@
+import { isSVGFile } from '@open-pencil/scene-graph/images'
+
import type {
ImageAttachmentMediaType,
PreparedImageAttachment
@@ -58,13 +60,6 @@ function canvasToBlob(
})
}
-/** Whether a file is an SVG image, which some systems report without a media type. */
-export function isSVGFile(file: File): boolean {
- return (
- file.type === 'image/svg+xml' || (file.type === '' && file.name.toLowerCase().endsWith('.svg'))
- )
-}
-
/** Whether a file can be attached as an image, as it is or after drawing an SVG as PNG. */
export function isAttachableImageFile(file: File): boolean {
return file.type.startsWith('image/') || isSVGFile(file)
diff --git a/src/components/chat/input/useAttachments.ts b/src/components/chat/input/useAttachments.ts
index 239ed1f3e..02060a8ef 100644
--- a/src/components/chat/input/useAttachments.ts
+++ b/src/components/chat/input/useAttachments.ts
@@ -3,11 +3,11 @@ import { uniq } from 'es-toolkit'
import { computed, onBeforeUnmount, ref, type Ref } from 'vue'
import type { Editor } from '@open-pencil/core'
+import { isSVGFile } from '@open-pencil/scene-graph/images'
import {
createImagePreviewURL,
isAttachableImageFile,
- isSVGFile,
rasterizeSVGAttachment,
revokeImagePreviewURL,
validateImageAttachmentFile
diff --git a/tests/app/automation/bridge/export.test.ts b/tests/app/automation/bridge/export.test.ts
index f198cc889..c460399f7 100644
--- a/tests/app/automation/bridge/export.test.ts
+++ b/tests/app/automation/bridge/export.test.ts
@@ -7,8 +7,8 @@ import { SkiaRenderer } from '@open-pencil/core/canvas'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
import { parseFigFile } from '@open-pencil/core/io/formats/fig'
import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
-import { pngSize } from '@open-pencil/fig'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { imageSize } from '@open-pencil/scene-graph/images'
import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'
import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'
@@ -91,7 +91,7 @@ describe('automation export of a page that is not on screen', () => {
args: { ids: [frame.id] }
})
- expect(pngSize(resultBytes(response))).toEqual({ width: 40, height: 30 })
+ expect(imageSize(resultBytes(response))).toEqual({ width: 40, height: 30 })
expect(store.state.currentPageId).toBe(shown)
})
@@ -106,7 +106,7 @@ describe('automation export of a page that is not on screen', () => {
args: {}
})
- expect(pngSize(resultBytes(response))).toEqual({ width: 50, height: 20 })
+ expect(imageSize(resultBytes(response))).toEqual({ width: 50, height: 20 })
expect(store.state.currentPageId).toBe(shown)
})
@@ -123,7 +123,7 @@ describe('automation export of a page that is not on screen', () => {
format: 'png'
})
- expect(pngSize(resultBytes(response))).toEqual({ width: 60, height: 25 })
+ expect(imageSize(resultBytes(response))).toEqual({ width: 60, height: 25 })
expect(store.state.currentPageId).toBe(shown)
})
@@ -133,7 +133,7 @@ describe('automation export of a page that is not on screen', () => {
const response = await handleTargetCommand(target(store, pageId), 'export', { scope: 'page' })
- expect(pngSize(resultBytes(response))).toEqual({ width: 70, height: 35 })
+ expect(imageSize(resultBytes(response))).toEqual({ width: 70, height: 35 })
expect(store.state.currentPageId).toBe(shown)
})
@@ -165,7 +165,7 @@ describe('automation export of a page that is not on screen', () => {
const response = await handleTargetCommand(target(store, other), 'export', { scope: 'page' })
- expect(pngSize(resultBytes(response))).toEqual({ width: 80, height: 20 })
+ expect(imageSize(resultBytes(response))).toEqual({ width: 80, height: 20 })
expect(store.state.currentPageId).toBe(shown)
})
})