vue中图片进行压缩之后在上传后端

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .original {
      width: 20px;
      height: 20px;
    }
  </style>
</head>
<body>
  <input type="file" onchange="updateFile(event)">
    <select id="sel">
      <option>1.0</option>
      <option>0.9</option>
      <option>0.5</option>
      <option>0.1</option>
    </select>
    <a class="generate" onClick="generate()">生成</a>
    <div class="original" id="original"></div>
    <div class="production" id="production"></div>
  <script>
    /**
   * 给input绑定事件
   */
  async function updateFile(e) {
    const file = e.target.files[0];
    if (!verify(file)) {
      //参数校验
      return false;
    }
    const base64Code = await getBase64(file); //获取base64编码
    placeImg(base64Code); //放置图片
  }
  /**
   * 参数校验
   * @param {*} file
   */
  function verify(file) {
    const { size, type } = file;
    if (size > 5 * 1024 * 1024) {
      alert('上传图片大小不能超过5M');
      return false;
    }
    if ('image/png' !== type) {
      alert('请上传图片');
      return false;
    }
    return true;
  }
  function getBase64(file) {
    return new Promise((resolve) => {
      const fileReader = new FileReader();
      fileReader.onload = (e) => {
        resolve(e.target.result);
      };
      fileReader.readAsDataURL(file);
    });
  }
  /**
   * 给图片设置合适的宽高放置在容器中
   */
  function placeImg(code) {
    const target = document.getElementById('original');
    const max_width = parseInt(getComputedStyle(target).width);
    const max_height = parseInt(getComputedStyle(target).height);
    let width, height;
    const image = new Image();
    image.src = code;
    image.onload = () => {
      const naturalWidth = image.naturalWidth;
      const naturalHeight = image.naturalHeight;
      const radio = naturalWidth / naturalHeight;
      if (radio >= 1) {
        //宽比高大
        width = naturalWidth < max_width ? naturalWidth : max_width;
        height = (width * 1) / radio;
        if (height > max_height) {
          height = max_height;
          width = height * radio;
        }
      } else {
        height = naturalHeight < max_height ? naturalHeight : max_height;
        width = height * radio;
        if (width > max_width) {
          width = max_width;
          height = (width * 1) / radio;
        }
      }
      width = parseInt(width);
      height = parseInt(height);
      image.style.width = `${width}px`;
      image.style.height = `${height}px`;
      target.innerHTML = '';
      target.appendChild(image);
      img = image; //将预览图对象赋值给全局变量img
      compress();
    };
  }

/**
   * 压缩图片
   */
   function compress() {
    if (!img) { //img是预览图对象
      return false;
    }

    const value = Number(document.getElementById('sel').value);
    const canvas = document.createElement('CANVAS');
    const w = img.width,
          h = img.height;
    canvas.width = w;
    canvas.height = h;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, w, h);
    const code = canvas.toDataURL('image/png', value);
    const image = new Image();
    image.src = code;
    image.onload = () => {
      const des = document.getElementById('production');
      des.innerHTML = '';
      des.appendChild(image);
      compress_img = image;
    };
  }
  /**
   * 下载图片
   * @param {*}
   */
  function generate() {
    if (!compress_img) {
      return false;
    }
    const a = document.createElement('A');
    a.href = compress_img.src;
    a.download = 'download';
    a.click();
  }
  </script>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在uniapp框架,可以通过以下步骤封装一个对后端请求的图片压缩功能: 1. 在uniapp项目,创建一个工具类文件,例如util.js。 2. 在util.js,引入第三方图片压缩库,例如compressorjs。可以通过npm安装该库,然后使用import引入。 3. 在util.js,定义一个图片压缩函数,例如compressImage。该函数接受两个参数:图片的base64字符串和压缩后的最大宽度。函数的实现如下: ```javascript import Compressor from 'compressorjs'; function compressImage(base64, maxWidth) { return new Promise((resolve, reject) => { new Compressor(base64, { maxWidth, success(result) { resolve(result); }, error(err) { reject(err); }, }); }); } ``` 4. 在需要发送图片请求的地方,调用compressImage函数对图片进行压缩,然后再发送请求。例如: ```javascript import { api } from '@/api'; import { compressImage } from '@/utils/util'; async function uploadImage(file) { const base64 = await readFile(file); const compressed = await compressImage(base64, 800); const formData = new FormData(); formData.append('image', compressed); const response = await api.uploadImage(formData); return response.data; } ``` 其,readFile函数用于将文件转换为base64字符串,api.uploadImage函数用于发送图片上传请求。在发送请求时,将压缩后的图片作为formData的一个字段,即可实现图片压缩功能。 通过以上步骤,我们就成功地在uniapp框架封装了一个对后端请求的图片压缩功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@前端小菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值