0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Canvas の書き出し後に Blob.type から拡張子を決める

0
Posted at

Canvas に WebP を指定しても、ブラウザーがその形式に対応していなければ PNG が返ります。書き出しの指定値でファイル名を組み立てると、PNG に .webp という名前が付くことがあります。

拡張子はコールバックで受け取った Blob の type から決めます。Blob が null ならファイル名は作りません。

function fileExtension(blob) {
  switch (blob.type) {
    case "image/png": return ".png";
    case "image/jpeg": return ".jpg";
    case "image/webp": return ".webp";
    default: throw new Error("Unsupported output type");
  }
}

canvas.toBlob((blob) => {
  if (blob === null) return;
  const filename = "preview" + fileExtension(blob);
  console.log(filename);
}, "image/webp");

PNG と WebP をそれぞれ指定して、出力された type と拡張子を確認します。PNG に戻った場合も、ファイル名は .png になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?