1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Web ブラウザで文字列を Data URL に変換する

Last updated at Posted at 2023-01-10

備忘録。

ASCII 文字のみの場合

function stringToDataURL(str) {
  return "data:text/plain;base64, " + btoa(str)
}
stringToDataURL("Hello, World!") //=> "data:text/plain;base64, SGVsbG8sIFdvcmxkIQ=="

image.png

(2023.01.12 追記) マルチバイト文字を含む場合

btoa を使うやり方だとマルチバイト文字が含まれている場合にエラーが出てしまうとコメントでご指摘いただいた。その場合は Blob に変換してから FileReader の readAsDataURL を使ったほうが良さそう。(こちらは非同期関数になるが)

function stringToDataURL(str, type = 'text/plain;charset=utf-8') {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.addEventListener('load', () => resolve(fileReader.result))
    fileReader.addEventListener('error', () => reject(fileReader.error))
    fileReader.readAsDataURL(new Blob([str], { type }))
  })
}
const dataUrl = await stringToDataURL("あいうえお") //=> "data:text/plain;base64,44GC44GE44GG44GI44GK"
1
1
5

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?