zoukankan      html  css  js  c++  java
  • 前端实现图片压缩(两种方法)

    
    
    样例3:
    // img.onload = () => {
        //   const originWidth = img.width;
        //   const originHeight = img.height;
        //   const maxWidth = 1600;
        //   const maxHeight = 1200;
        //   let targetWidth = originWidth;
        //   let targetHeight = originHeight;
        //   if (originWidth > maxWidth || originHeight > maxHeight) {
        //     if (originWidth / originHeight > maxWidth / maxHeight) {
        //       // 更宽,按照宽度限定尺寸
        //       targetWidth = maxWidth;
        //       targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        //     } else {
        //       targetHeight = maxHeight;
        //       targetWidth = Math.round(maxHeight * (originWidth / originHeight));
        //     }
        //   };
        //   // canvas对图片进行缩放
        //   canvas.width = targetWidth;
        //   canvas.height = targetHeight;
        //
        //   // 清除画布
        //   context.clearRect(0, 0, targetWidth, targetHeight);
        //   // 图片压缩
        //   context.drawImage(img, 0, 0, targetWidth, targetHeight);
        //   canvas.toBlob(
        //     blob => {
        //       console.log('beibeippppp', blob);// blob {size:31784, type: "image/jpeg"}
        //       setCanvasToBlob(blob);
        //     },
        //     'image/jpeg',
        //     0.7,
        //   );
        //   // const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        //   // const code = jsQR(imageData.data, imageData.width, imageData.height);
        // };
        // img.onerror = () => console.error('Upload file of image format please.');
    
    
    
    样例1:
    import React from 'react';
    import {ImagePicker, Toast} from 'antd-mobile';
    import './style.less';
    
    
    const BznImagesPicker = (props) => {
    
      const maxSize = 3027;
    
      const handleChange = (files, operationType, index) => {
        if (operationType === 'add') {
          const file = [...files].pop().file;
          if (file.size > 3 * 1024 * 1024) {
            let rate = 0.6;
            let reader = new FileReader();
            reader.readAsDataURL(file);
            let img = new Image();
            reader.onload = function (e) {
              img.src = e.target.result;
            };
            img.onload = function () {
              let canvas = document.createElement('canvas');
              let context = canvas.getContext('2d');
              // 文件大小KB
              const fileSizeKB = Math.floor(file.size / 1024);
              // console.log('file size:', fileSizeKB, 'kb');
              // 配置rate和maxSize的关系
              if (fileSizeKB * rate > maxSize) {
                rate = Math.floor(maxSize / fileSizeKB * 10) / 10;
                // console.log('file rate:', rate);
                // console.log('file size*rate:', fileSizeKB * rate, 'kb');
              }
              // 缩放比例,默认0.5
              let targetW = canvas.width = this.width * rate;
              let targetH = canvas.height = this.height * rate;
              context.clearRect(0, 0, targetW, targetH);
              context.drawImage(img, 0, 0, targetW, targetH);
              canvas.toBlob(function (blob) {
                const newImage = new File([blob], file.name, {type: file.type});
                // console.log(newImage.size / 1024, 'kb');
                props.onChange && props.onChange([{file: newImage}], operationType, index);
              });
            };
          } else {
            props.onChange && props.onChange(files, operationType, index);
          }
        } else {
          props.onChange && props.onChange(files, operationType, index);
        }
      };
    
      const handleImageClick = (index, files) => {
        props.onImageClick && props.onImageClick(index, files);
      };
    
      return (
        !props.hidden
          ? <div className='imagePickerItem'>
            {
              props.label ? <div className='imagePickerLabel'>{props.label}</div> : ''
            }
            <ImagePicker
              files={props.files}
              onChange={handleChange}
              onImageClick={handleImageClick}
              selectable={props.files.length < props.filesLength}
              multiple={props.multiple}
            />
          </div> : ''
      );
    };
    
    export default BznImagesPicker;
    
    
    
    样例二:
    img.onload = () => {
            const originWidth = img.width;
            const originHeight = img.height;
            const maxWidth = 1600;
            const maxHeight = 1200;
            let targetWidth = originWidth;
            let targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽,按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
            }
            // canvas对图片进行缩放
            canvas.width = targetWidth;
            canvas.height = targetHeight;
    
            // 清除画布
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片压缩
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            canvas.toBlob(
              blob => {
                const newImage = new File([blob as any], (imageFile as any).name, { type: (imageFile as any).type });
                console.log('beibeicai2222blob', blob, newImage); // blob {size:31784, type: "image/jpeg"}
                // setCanvasToBlob(blob);
              },
              (imageFile as any).type,
              0.7,
            );
          };
          img.onerror = () => console.error('Upload file of image format please.');
  • 相关阅读:
    理解二进制操作
    web前端代码重构
    Tomcat是一个Servlet容器?
    对于python命令行参数使用,你应该这么做才专业
    利用深度学习识别滑动验证码缺口位置
    机器学习笔记(十)---- KNN(K Nearst Neighbor)
    基于NB-IoT的智慧路灯监控系统(项目简介)
    【读一本书】《昇腾AI处理器架构与编程》--神经网络基础知识(2)
    高性能Web动画和渲染原理系列(4)“Compositor-Pipeline演讲PPT”学习摘要【华为云技术分享】
    华为云数据库亮相下一代数据技术发展论坛,助力“数字一带一路”
  • 原文地址:https://www.cnblogs.com/chenbeibei520/p/12534798.html
Copyright © 2011-2022 走看看