Skip to content

Commit

Permalink
Output as JPEG if browser doesn't support WebP
Browse files Browse the repository at this point in the history
This is necessary to avoid unexpectedly large files in Safari.
  • Loading branch information
theodorejb committed Nov 14, 2023
1 parent 00dd125 commit 1ab6277
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cropt",
"version": "0.8.4",
"version": "0.8.6",
"description": "A lightweight JavaScript image cropper",
"files": [
"src/cropt.*"
Expand Down
11 changes: 11 additions & 0 deletions src/cropt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,13 @@ function getArrowKeyDeltas(key: string): [number, number] {
}
}

function canvasSupportsWebP() {
// https://caniuse.com/mdn-api_htmlcanvaselement_toblob_type_parameter_webp
return document.createElement('canvas')
.toDataURL('image/webp')
.startsWith('data:image/webp');
}

type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
Expand Down Expand Up @@ -252,6 +259,10 @@ export class Cropt {
}

toBlob(size: number | null = null, type = "image/webp", quality = 1): Promise<Blob> {
if (type === "image/webp" && quality < 1 && !canvasSupportsWebP()) {
type = "image/jpeg";
}

return new Promise((resolve, reject) => {
this.toCanvas(size).then((canvas) => {
canvas.toBlob((blob) => {
Expand Down

0 comments on commit 1ab6277

Please sign in to comment.