|
7 | 7 | import { markRaw } from 'vue'
|
8 | 8 | import { getMimeFromExt } from '@/utils/file'
|
9 | 9 | import { extname } from '@/utils/path'
|
10 |
| -import type { Disposer } from '@/utils/disposable' |
| 10 | +import { Disposable, type Disposer } from '@/utils/disposable' |
11 | 11 | import { Cancelled } from '@/utils/exception'
|
| 12 | +import type { Size } from '.' |
12 | 13 |
|
13 | 14 | export type Options = {
|
14 | 15 | /** MIME type of file */
|
@@ -121,6 +122,41 @@ export async function toConfig(file: File) {
|
121 | 122 | return JSON.parse(text) as unknown
|
122 | 123 | }
|
123 | 124 |
|
| 125 | +async function getSVGImageSize(svgFile: File) { |
| 126 | + const svgText = await toText(svgFile) |
| 127 | + const parser = new DOMParser() |
| 128 | + const svg = parser.parseFromString(svgText, 'image/svg+xml').documentElement |
| 129 | + if (!(svg instanceof SVGSVGElement)) throw new Error(`invalid svg: ${svgFile.name}`) |
| 130 | + // Keep consistent with spx, for details see https://github.com/goplus/spx/blob/15b2e572746f3aaea519c2d9c0027188b50b62c8/internal/svgr/svg.go#L39 |
| 131 | + const { width, height } = svg.viewBox.baseVal |
| 132 | + return { width, height } |
| 133 | +} |
| 134 | + |
| 135 | +async function getBitmapImageSize(bitmapImgFile: File) { |
| 136 | + const d = new Disposable() |
| 137 | + const imgUrl = await bitmapImgFile.url((fn) => d.addDisposer(fn)) |
| 138 | + return new Promise<Size>((resolve, reject) => { |
| 139 | + const img = new window.Image() |
| 140 | + img.src = imgUrl |
| 141 | + img.onload = () => { |
| 142 | + resolve({ |
| 143 | + width: img.width, |
| 144 | + height: img.height |
| 145 | + }) |
| 146 | + } |
| 147 | + img.onerror = (e) => { |
| 148 | + reject(new Error(`load image failed: ${e.toString()}`)) |
| 149 | + } |
| 150 | + }).finally(() => { |
| 151 | + d.dispose() |
| 152 | + }) |
| 153 | +} |
| 154 | + |
| 155 | +export async function getImageSize(file: File) { |
| 156 | + if (file.type === 'image/svg+xml') return getSVGImageSize(file) |
| 157 | + return getBitmapImageSize(file) |
| 158 | +} |
| 159 | + |
124 | 160 | export function listDirs(
|
125 | 161 | files: { [path: string]: unknown },
|
126 | 162 | /** path of parent dir to do list, with no tailing slash */
|
|
0 commit comments