cropperjs上傳圖片截取

cropperjs上傳圖片截取

參考:http://www.reibang.com/p/9dc2f643cb6a
參考:http://www.reibang.com/p/4fc756df20f9

  • 首先下載依賴npm i cropperjs眷蜈,這里上傳用到了ali-oss拜英,所以同時(shí)安裝ali-oss的依賴npm i ali-oss
  • 組件代碼如下
<template>
  <div class="v-simple-cropper">
    <!-- <input class="file" type="file" accept="image/*" @change="uploadChange" /> -->
    <van-uploader
      v-model="fileList"
      :after-read="afterRead"
      :before-delete="beforeDelete"
      :max-count="1"
      image-fit="contain"
    />
    <div class="tip">請(qǐng)上傳一寸免冠照片</div>
    <div class="v-cropper-layer" ref="layer" v-show="showlayer">
      <div class="layer-header">
        <button class="cancel" @click="cancelHandle">取消</button>
        <button class="cancel" @click="cropperRotate(90)">旋轉(zhuǎn)</button>
        <button class="confirm" @click="confirmHandle">選取</button>
      </div>
      <img ref="cropperImg" />
    </div>
  </div>
</template>

<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.min.css";
import { getALiYun } from "@/api/dict";
import { client } from "@/utils/alioss";
export default {
  name: "Cropper",
  props: {
    fileUrl: String,
    uploadURL: Function,
    deleteURL: Function,
  },
  data() {
    return {
      cropper: null,
      showlayer: false,
      initParam: {
        scale: 1, // 相對(duì)手機(jī)屏幕放大的倍數(shù)
      },
      fileList: [],
      ALiYun: {},
    };
  },
  created() {
    this.getALiYun();
  },
  mounted() {
    this.init();
    if (this.fileUrl) {
      const index = this.fileUrl.lastIndexOf("/");
      const name = this.fileUrl.substr(index + 1);
      let obj = {
        content: this.fileUrl,
        url: this.fileUrl,
        name: decodeURIComponent(name),
      };
      this.fileList.push(obj);
    }
  },
  methods: {
    // 獲取后臺(tái)OSS數(shù)據(jù)源
    async getALiYun() {
      getALiYun().then((res) => {
        if (res.code === 200) {
          this.ALiYun = res.data;
        }
      });
    },
    // 初始化
    init() {
      const cropperImg = this.$refs.cropperImg;
      this.cropper = new Cropper(cropperImg, {
        aspectRatio: 446 / 650, // 剪裁比例
        dragMode: "move",
        viewMode: 1,
        cropBoxResizable: false,
      });
    },
    // 選擇圖片
    afterRead(file) {
      // 判斷擴(kuò)展名
      const tmpCnt = file.file.name.lastIndexOf(".");
      const exName = file.file.name.substring(tmpCnt + 1);
      const names = ["jpg", "jpeg", "png"];
      if (names.indexOf(exName) < 0) {
        this.fileList = [];
        this.$Toast.fail("不支持的格式!");
        return;
      }
      this.fileList[0].status = "uploading";
      this.fileList[0].message = "上傳中..";
      const URL = window.URL || window.webkitURL;
      let binaryData = [];
      binaryData.push(file.file);
      this.cropper.replace(URL.createObjectURL(new Blob(binaryData)));
      this.showlayer = true;
    },
    // 旋轉(zhuǎn)
    cropperRotate(val) {
      this.cropper.rotate(val);
    },
    cancelHandle() {
      this.cropper.reset();
      this.fileList = [];
      this.showlayer = false;
    },
    confirmHandle() {
      const cropBox = this.cropper.getCropBoxData();
      const scale = this.initParam["scale"] || 1;
      this.cropper
        .getCroppedCanvas({
          width: cropBox.width * scale,
          height: cropBox.height * scale,
        })
        //把裁剪的圖片轉(zhuǎn)換成blob類型文件,在通過(guò)new File()低散,轉(zhuǎn)換成file文件
        .toBlob(async (blob) => {
          //重置file的name,以時(shí)間戳作為文件名
          const timeString = new Date().getTime();
          const imgFile = new File([blob], `${timeString}.jpg`, {
            type: "image/jepg",
          });
          this.showlayer = false;
          const res = await this.uploadFile(imgFile);
          this.$emit("uploadURL", res);
        });
    },
    uploadFile(file) {
      return new Promise((resolve) => {
        const fileName = `${Date.parse(new Date())}/${file.name}`; //定義唯一的文件名
        return client(this.ALiYun)
          .put(fileName, file)
          .then(({ res, url, name }) => {
            if (res && res.status == 200) {
              console.log("阿里云OSS上傳成功");
              let obj = {
                name: file.name,
                content: url,
                file,
              };
              this.fileList = [];
              this.fileList.push(obj);
              resolve(url);
            } else {
              this.fileList = [];
              this.$Toast.fail("上傳失敗");
            }
          })
          .catch((err) => {
            console.log(`阿里云OSS上傳失敗回調(diào)`, err);
          });
      });
    },
    beforeDelete(){
      this.fileList = [];
      this.$emit("deleteURL");
    }
  },
};
</script>
<style lang="less" scoped>
.v-simple-cropper {
  // width: 100%;
  // height: 100%;
  // position: absolute;
  // left: 0;
  // top: 0;
  text-align: center;
  padding-top: 10px;
  // .file {
  //   // width: 100%;
  //   // height: 100%;
  //   // opacity: 0;
  //   // width: 100px;
  //   height: 100px;
  // }
  .tip {
    font-size: 14px;
    margin: 5px 0;
  }

  /deep/.van-uploader__upload {
    margin: 0 !important;
  }
  .v-cropper-layer {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    z-index: 99999;
    .layer-header {
      position: absolute;
      bottom: 0;
      left: 0;
      z-index: 99999;
      background: rgba(#fff, 0.5);
      width: 100%;
      height: 1.5rem;
      padding: 0 0.2rem;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
    }
    .cancel,
    .confirm {
      line-height: 1.5rem;
      font-size: 0.58rem;
      background: none;
      border: 0;
      outline: 0;
      // float: left;
    }
    // .confirm {
    //   // float: right;
    // }
    img {
      position: inherit !important;
      border-radius: inherit !important;
      float: inherit !important;
    }
  }
}
</style>
  • 頁(yè)面引入及使用代碼如下
<Cropper
  @uploadURL="uploadURL"
  @deleteURL="deleteURL"
  :fileUrl="infoForm.personalPhoto"
 />

import Cropper from "@/components/Cropper/index.vue";
components: {
    Cropper,
  },
// 獲取圖片url
    uploadURL(url) {
      console.log(url, "1111111111111111");
    },
    deleteURL() {
      this.infoForm.personalPhoto = "";
    },
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末快集,一起剝皮案震驚了整個(gè)濱河市笛臣,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌尸饺,老刑警劉巖进统,帶你破解...
    沈念sama閱讀 222,681評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異浪听,居然都是意外死亡螟碎,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門迹栓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)掉分,“玉大人,你說(shuō)我怎么就攤上這事克伊∷止” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 169,421評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵愿吹,是天一觀的道長(zhǎng)不从。 經(jīng)常有香客問(wèn)我,道長(zhǎng)犁跪,這世上最難降的妖魔是什么椿息? 我笑而不...
    開(kāi)封第一講書人閱讀 60,114評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮坷衍,結(jié)果婚禮上撵颊,老公的妹妹穿的比我還像新娘。我一直安慰自己惫叛,他們只是感情好倡勇,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般妻熊。 火紅的嫁衣襯著肌膚如雪夸浅。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 52,713評(píng)論 1 312
  • 那天扔役,我揣著相機(jī)與錄音帆喇,去河邊找鬼。 笑死亿胸,一個(gè)胖子當(dāng)著我的面吹牛坯钦,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播侈玄,決...
    沈念sama閱讀 41,170評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼婉刀,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了序仙?” 一聲冷哼從身側(cè)響起突颊,我...
    開(kāi)封第一講書人閱讀 40,116評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎潘悼,沒(méi)想到半個(gè)月后律秃,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡治唤,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評(píng)論 3 342
  • 正文 我和宋清朗相戀三年棒动,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宾添。...
    茶點(diǎn)故事閱讀 40,865評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡船惨,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出辞槐,到底是詐尸還是另有隱情掷漱,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布榄檬,位于F島的核電站卜范,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏鹿榜。R本人自食惡果不足惜海雪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望舱殿。 院中可真熱鬧奥裸,春花似錦、人聲如沸沪袭。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,699評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至侠鳄,卻和暖如春埠啃,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背伟恶。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,814評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工碴开, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人博秫。 一個(gè)月前我還...
    沈念sama閱讀 49,299評(píng)論 3 379
  • 正文 我出身青樓潦牛,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親挡育。 傳聞我的和親對(duì)象是個(gè)殘疾皇子巴碗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容