LoginSignup
0
0

More than 3 years have passed since last update.

htmlのinput imageでimageファイルをbase64に変換して取り扱うための関数

Posted at

htmlのinput imageでimageファイルをbase64に変換して取り扱うための関数

htmlのinput imageでimageファイルをbase64に変換して取り扱うための関数が見当たらなかったので作った。

demo

async/awaitで使ってください。
promiseでも良い

index.js
let image2base64 = input_id => new Promise((resolve, reject) => {
    let fileinput = document.getElementById(input_id);
    if (fileinput == null)
        reject("cant find element");

    let fileData = file.files[0]
    if (fileData === undefined)
        reject("no file")

    if (!fileData.type.match('image.*'))
        reject("file type error");

    let reader = new FileReader();
    reader.onload = () => {
        resolve(reader.result)
    }
    reader.readAsDataURL(fileData);
})

to use

<input type="file" accept='image/*' id="file"> で選択されたファイルを扱うとする。

// idを指定する
let b64 = await image2base64('file') 

// base64をテキストにする
document.getElementById("result").innerText = b64;

// base64をimg.srcにapply
document.getElementById("result2").src = b64;

demo

まあだいたいこんな感じ
デモに乗ってるソース

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script>
        let image2base64 = input_id => new Promise((resolve, reject) => {
            let fileinput = document.getElementById(input_id);
            if (fileinput == null)
                reject("cant find element");

            let fileData = file.files[0]
            if (fileData === undefined)
                reject("no file")

            if (!fileData.type.match('image.*'))
                reject("file type error");

            let reader = new FileReader();
            reader.onload = () => {
                resolve(reader.result)
            }
            reader.readAsDataURL(fileData);
        })
        let henkan = async () => {
            let b64 = await image2base64('file')
            document.getElementById("result").innerText = b64;
            document.getElementById("result2").src = b64;
        }
    </script>
</head>
<body>
<input type="file" accept='image/*' id="file">
<button onclick="henkan()">変更</button>
<div id="result"></div>
<img id="result2">

</body>
</html>
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