1
1

More than 1 year has passed since last update.

【Vue.js】画像を圧縮、リサイズ、リネームしてダウンロードする

Last updated at Posted at 2022-03-06

使用したライブラリ

browser-image-compression

file-saver

ここでは上記の2つのライブラリを使用する。

ライブラリのインストール

npmもしくはyarnでインストール。

npm install browser-image-compression
or
yarn add browser-image-compression
npm install file-saver
or
yarn add file-saver

画像圧縮・リサイズ・リネーム・ダウンロードの流れ

  1. フォームでの画像の選択時、画像をscriptで受け取る
  2. 受け取った画像を圧縮・リサイズ・リネームする
  3. 自動で画像をダウンロードする
ImageResize.vue (template部分)
<template>
  <div>
    <p>画像名を入れてください</p>
    <input type="text" v-model="imageName" />
    <input
      type="file"
      accept="image/*"
      label="写真"
      ref="preview"
      @change="handleImageUpload()"
    />
  </div>
</template>
ImageResize.vue (script部分)
<script>
import imageCompression from 'browser-image-compression'
import { saveAs } from "file-saver"

export default {
data() {
  return {
    imageName: "", 
  }
},
methods: {
  handleImageUpload() {
    const imageFile = this.$refs.preview.files[0];

    const options = {
      maxSizeMB: 1, // 圧縮サイズの最大値を指定
      maxWidthOrHeight: 400, // 画像の縦横を指定 (比率で縮小)
      useWebWorker: true
    }
    imageCompression(imageFile, options)
      .then((compressedFile) => {
        saveAs(compressedFile, this.imageName); // 画像のダウンロード
      })
      .catch((error) => {
        console.log(error.message);
      });
    }
  }
}
</script>

今までは画像加工ツールを使用して1枚1枚加工していたのですが、
これで簡単に画像の圧縮、リサイズ、リネームができるようになりました!

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