Skip to content

Commit

Permalink
feat: support data url as Image#src (#941)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn authored Nov 15, 2024
1 parent cd5e342 commit 8686c8b
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 6 deletions.
35 changes: 35 additions & 0 deletions __test__/image.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,38 @@ test('should throw if src path is invalid', async (t) => {
},
)
})

test('should be able to set data url as Image src', async (t) => {
const image = new Image()
const { promise, resolve } = Promise.withResolvers<void>()
image.onload = () => {
resolve()
}
const imagePath = `data:image/png;base64,${await fs.readFile(join(__dirname, '../example/simple.png'), 'base64')}`
image.src = imagePath
await promise
t.is(image.width, 300)
t.is(image.height, 320)
t.is(image.naturalWidth, 300)
t.is(image.naturalHeight, 320)
t.is(image.src, imagePath)
})

test('should trigger onerror if src data url is invalid', async (t) => {
await t.throwsAsync(
() =>
new Promise((_, reject) => {
const image = new Image()
image.onload = () => {
reject(new Error('should not be called'))
}
image.onerror = (err) => {
reject(err)
}
image.src = 'data:image/png;base64,invalid'
}),
{
message: 'Decode data url failed Base64Error',
},
)
})
2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ export class Image {
readonly naturalHeight: number
readonly complete: boolean
alt: string
// the src can be a Uint8Array or a string
// if it's a string, it can be a file path, a data URL, a remote URL, or a SVG string
src: Uint8Array | string
onload?(): void
onerror?(err: Error): void
Expand Down
18 changes: 12 additions & 6 deletions src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,12 +353,18 @@ impl Task for BitmapDecoder {
fn compute(&mut self) -> Result<Self::Output> {
let data_ref = match self.data.as_ref() {
Some(Either::A(data)) => Cow::Borrowed(data.as_ref()),
Some(Either::B(path)) => Cow::Owned(std::fs::read(path).map_err(|io_err| {
Error::new(
Status::GenericFailure,
format!("Failed to read {}: {io_err}", path),
)
})?),
Some(Either::B(path_or_svg)) => {
if path_or_svg.starts_with("data:image") {
Cow::Borrowed(path_or_svg.as_bytes())
} else {
Cow::Owned(std::fs::read(path_or_svg).map_err(|io_err| {
Error::new(
Status::GenericFailure,
format!("Failed to read {}: {io_err}", path_or_svg),
)
})?)
}
}
None => {
return Ok(DecodedBitmap {
bitmap: DecodeStatus::Empty,
Expand Down

0 comments on commit 8686c8b

Please sign in to comment.