Vue image processing solution, one article is enough

1. Reading Notes

This article compiled by Xiaoshuai has a lot of content, handsome you are worth reading, there is the core code of the solution, you can put it in the project and use it
directly Another article on photo editing", so stay tuned!

Second, the problem to be solved

  • Use canvas to handle image rotation and import problems
  • At present, it is possible to process image files on the front end and then transmit them to the server. It is not necessary to implement image processing logic on the server.

3. Knowledge reserve

  1. <input type="file">The File file format object obtained by using the label is as follows
    insert image description here
  2. Image Base64 encoded format (can <img> <el-image>be rendered directly using tags)
    insert image description here

4. Solutions

If you use canvas to realize the rotation of the picture, there are currently two options

  1. Using the translate()平移函数++ implementation of canvas , there are more complex mathematical calculation problems in this wayrotate()旋转函数drawImage()函数
  2. Using rotate()旋转函数the + drawImage()函数implementation of canvas (the solution used in this article), the code case is provided below

5. Core code

  • The core code corresponding to solution 2 solves the problem of rotating the picture clockwise by 90°, 180°, and 270°
  • drawImage()The parameters in the following code function imgare new Image() objects, or other parameter types that meet the requirements of the function
// 创建canvas
const selfCanvas = document.createElement('canvas')
const selfCtx = selfCanvas.getContext('2d')

if (angle == '90') {
    
     // 顺时针旋转90度
  selfCanvas.width = img.height
  selfCanvas.height = img.width
  selfCtx.rotate(90 * Math.PI / 180);
  selfCtx.drawImage(img, 0, 0, img.width, -img.height)       
} else if (angle == '180') {
    
     // 顺时针旋转180度
  selfCanvas.width = img.width
  selfCanvas.height = img.height
  selfCtx.rotate(180 * Math.PI / 180)
  selfCtx.drawImage(img, -img.width, -img.height, img.width, img.height)
} else if (angle == '270') {
    
     // 顺时针旋转270度
  selfCanvas.width = img.height
  selfCanvas.height = img.width
  selfCtx.rotate(270 * Math.PI / 180)
  selfCtx.drawImage(img, -img.width, 0, img.width, img.height)        
} else {
    
     // 不进行任何旋转
  selfCanvas.width = img.width
  selfCanvas.height = img.height
  selfCtx.drawImage(img, 0, 0, img.width, img.height)
}

6. References

  1. Get the URL of the image file File
img.src = URL.createObjectURL(imgFile)
  1. Related api function methods
  • createObjectURL(obj): Returns a URL object representing the specified File object (generate blob: http://www.xxxx.com/xx link, you can directly open the File content on the web page) or Blob object (for downloading), obj is a File object, Blob object or MediaSource object
  • revokeObjectURL(objURL): A new URL object is created every time the createObjectURL() method is called, even if you have already created it with the same object as a parameter. When these URL objects are no longer needed, each object must be released by calling the URL.revokeObjectURL() method, objURL is the object returned by URL.createObjectURL(obj)
  • arr = new Uint8Array(length): returns an 8-bit unsigned integer array with a length of length (the storage size is 0 to 256, negative numbers will be automatically converted to integers by adding 256, exceeding -256), and the content is initialized to 0 when created
  • new Blob(arr,options): Returns a blob object (which can be understood as a binary data object), commonly used for file downloads
  • canvas.toBlob(callback, type, quality): create a Blob object to display the picture on the canvas; this picture file can be cached or saved locally, specific parameters:
    • allback: callback function, which can get a single Blob object parameter. May get a null value if the image was not successfully created
    • type: Specifies the image format, the default format (not specified or not supported) is image/png
    • quality: The value is between 0 and 1, and it is used to specify the image display quality when the requested image format is image/jpeg or image/webp. If the value of this parameter is not within the specified type and range
  1. In h5, the camera can be called by using the two attributes of input type="file" and capture="camera"
  2. If you use document.createElement() to dynamically create elements, you can get the input value by the following method
// 创建一个input元素
var inputElem = document.createElement("input");
// 获取input的值
var inputValue = inputElem.value;
// 如果input标签type="file"
// 得到文件对象File
var file = inputElem.files
  1. If the input tag is not created dynamically but is an already written html element, you can e.target.filesget the file object in change="methodsName(e)"
  2. In Vue, events can be added and removed in the following ways
// 绑定事件 可以进行监听
addEventListener()
// 移除事件
removeEventListener()
  1. Regarding <input>the webkitdirectory attribute reference in the tag:https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/webkitdirectory
  2. Upload files using FormData object
const formData = new FormData()
formData.append('file', File)

Seven, FileReader () object

  • The FileReader object allows a Web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer, using a File or Blob object to specify the file or data to read.
  • The FileReader instance has 4 methods, 3 for reading files and one for interrupting reading
    • abort parameter none interrupt reading
    • readAsBinaryString parameter file reads the file as binary code
    • The readAsDataUrl parameter file reads the file as a string starting with data:, the essence is that the Data URL is a solution to embed small files (images, etc.) directly into the document, and the base64 method is obtained from this
    • readAsText file,[encoding] read the file in text mode, the read result is the content of the text
  • The reading result will be stored in the result attribute of FileReader, and the brief introduction of handling events:
    • Triggered when onabort is interrupted
    • onerror Triggered when an error occurs
    • onload Triggered when the read is successful
    • onloadend triggers when the read is complete regardless of success or failure
    • onloadstart fires when reading starts
    • onprogress reading
  • After the file starts to be read, the result attribute will be filled regardless of success or failure. If the reading fails, the result attribute will be assigned a value of null, otherwise the read result will be filled.
  • After onload reads successfully, directly assign base64 to the src attribute of the img element, and you can preview the image
  • Use the FileReader object to convert File to base64 code case
// 图片file转base64方法(file文件,回调函数)
  fileToBase64(file, callback) {
    
    
    // 创建FileReader对象(不兼容IE)
    let reader = new FileReader();
    // 将file转为base64 (异步操作)
    reader.readAsDataURL(file); 
    // 转换成功
    reader.onload = () => {
    
    
      const response = {
    
    
        status: true,
        data: reader.result
      }
      callback(response);
    };
    // 转换失败
    reader.onerror = function () {
    
    
      const response = {
    
    
        status: false,
        data: reader.error
      }
      callback(response);
    };
  }

// 调用方法
fileToBase64(imgFile, (res) => {
    
    
  if(res.status) {
    
    
    console.log('file转化成base64成功---',res.data)
  } else {
    
    
    console.log('file转化base64失败---',res.data)
  }
})

8. Use of Exif library

  1. Use Exif to obtain the original data of the image, such as: photo direction, shooting event, ISO sensitivity, GPS location and other data
  2. Introduce exif-js into vue
npm install exif-js --save   
  1. Some API methods provided by Exif
    • Exif.getData(img,callback) Get image data
    • Exif.getTag(img,tag) Get a certain data of the image
    • Exif.getAllTags(img) Get all the data of the image
    • Exif.pretty(img) Get all the data of the image, and the value ranges in the form of a string
  • orientationDifferent values ​​in Exif represent different directions
  1. Exif's npm warehouse address:https://www.npmjs.com/package/exif-js
  2. GitHub address of Exif: https://github.com/exif-js/exif-js
    There are reference documents in the above two addresses
  3. Front-end development toolbox:http://code.ciaoca.com/

Nine, Canvas canvas

  1. Canvas is a container (canvas), and its getContext() method is used to obtain an object that provides methods and properties for drawing on the canvas
  2. Information about canvas in the rookie tutorial:https://www.runoob.com/tags/ref-canvas.html
  3. Canvas data in w3school:https://www.w3school.com.cn/jsref/dom_obj_canvas.asp
  4. Information website:https://www.twle.cn/l/yufei/canvas/canvas-basic-index.html

10. Dynamically create tags and add binding events

var input = document.createElement('input'); 
input.setAttribute('value', ''); 
input.setAttribute('type', 'text'); 
input.setAttribute('class', 'my-custom-input'); 

document.body.appendChild(input); 

//Change event listener 
input.addEventListener('change', function(e) {
    
     
    console.log('I just changed'); 
}, false);

Eleven, utils method

  1. Get the width and height of the image from the base64 code
var i = new Image();  //创建一个临时存储
i.onload = function(){
    
      //定义加载图片后弹出显示
 alert( i.width+", "+i.height );
};
i.src = imageData //将图片数据赋值即可
  1. base64 to file
dataURLtoFile(dataurl) {
    
    
    var arr = dataurl.split(',')
    var bstr = atob(arr[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
    
    
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], 'image', {
    
    
      type: 'image'
    })
  }

12. Image preview in vue

  1. Use remote <img>tags
  2. <el-image>Labels using element-ui
  3. Using element-ui<el-image-viewer>
<el-image-viewer v-if="imgViewerVisible" :on-close="closeImgViewer" :url-list="imgList" />
  1. Use the v-viewer library

13. Tools website

  1. base64 to image:http://www.atoolbox.net/Tool.php?Id=1024
  2. Vue picture cutting plug-in (vue-picture-cut 2.x):https://gitee.com/light-year/vue-picture-cut

Guess you like

Origin blog.csdn.net/baidu_38493460/article/details/130739528