LoginSignup
0
4

More than 3 years have passed since last update.

vue.js 画像をリサイズしてアップロード

Last updated at Posted at 2020-05-19

画像をリサイズしてアップロード。

javascript側で 画像を多少加工してPHPに送るとexif情報を失うので、
あとでPHPで対応することができない。
よって先にexifを元にjsで加工しておく必要がある。

参考
https://qiita.com/su_mi1228/items/f8f729a29f0b980f7e32

ボタンのデザインの変更
https://qiita.com/yasumodev/items/c9f8e8f588ded6b179c9

インストール


npm install --save blueimp-load-image

あとはコピペで動く



<template>

    <div>
        <input type="file" accept=".jpeg,.jpg,.png" @change="attachImg">
        <img :src="resizedImg">
    </div>

</template>



<script>

    import loadImage from 'blueimp-load-image';

    export default {

        data() {
            return {
                resizedImg: null
            };
        },

        methods: {

            attachImg(e) {

                const file = e.target.files[0];

                loadImage.parseMetaData(file, (data) => {

                    const options = {
                        maxHeight: 512,
                        maxWidth: 512,
                        canvas: true
                    };

                    if (data.exif) {
                        options.orientation = data.exif.get('Orientation');
                    }

                    this.displayImage(file, options);
                });
            },

            displayImage(file, options) {
                loadImage(
                    file,
                    async (canvas) => {
                        const data = canvas.toDataURL(file.type);

                        console.log(data);

                        // data_url形式をblob objectに変換
                        const blob = this.base64ToBlob(data, file.type);
                        // objectのURLを生成
                        const url = window.URL.createObjectURL(blob);
                        this.resizedImg = url; // resizedImgはdataで定義
                    },
                    options
                );
            },

            base64ToBlob(base64, fileType) {
                const bin = atob(base64.replace(/^.*,/, ''));
                const buffer = new Uint8Array(bin.length);
                for (let i = 0; i < bin.length; i++) {
                    buffer[i] = bin.charCodeAt(i);
                }
                return new Blob([buffer.buffer], {
                    type: fileType ? fileType : 'image/png'
                });
            }



        }
    }
</script>


0
4
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
4