Js image merge download (with code)

Idle time to have a tight mind, busy time to have leisure fun

This article has participated in the call for good writing activities, click to view: back end, big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!

directory

  • preface

  • The body of the

    • 1. Implementation steps
    • Two, code implementation
  • conclusion

  • Reference documentation

preface

Returns the directory

A few days ago I encountered a need for images to be downloaded and converted to file format. After comprehensive consideration, WE decided to use Canvas for implementation. This paper records the implementation process for your reference.

Requirements are as follows:

The user uploads an image, or passes in a list of image urls, composes a new image based on the number of images, one tile, two side by side, three glyph, four glyph, and returns a Blob object or Base64 format.

The body of the

1. Implementation steps

Returns the directory

The implementation steps are as follows:

  1. Obtain the list of pictures uploaded by users. Users can manually upload and pass the url list of pictures
  2. Process the list of images. If the user manually uploads the picture, get the element object directly to use; This is needed for image URL listsnew Image()Processing to a list of objects for reuse;
  3. To generate acanvasCanvas, usingdrawImageMethod According to a certain position to draw our rubbings.
  4. The generatedcanvasThe canvas is returned in the desired format (Blob object or Base64)
  5. usingaTag implementation download

Two, code implementation

Returns the directory

Because it is quite a simple function to achieve, so directly paste the code.

The Demo code:

<! DOCTYPEhtml>
<html>

<head>
  <meta charset="utf-8">
  <title>Realize picture merge download</title>
</head>
<style>
  .img_style {
    width: 30px;
    height: auto;
  }
</style>

<body>

  <fieldset>
    <input type="file" onchange="imageUpload(this,'#firstImg')">
    <img id="firstImg" class="img_style">
    <legend>Upload the figure 1</legend>
  </fieldset>
  <fieldset>
    <input type="file" onchange="imageUpload(this,'#secondImg')">
    <img id="secondImg" class="img_style">
    <legend>Upload the figure 2</legend>
  </fieldset>
  <fieldset>
    <input type="file" onchange="imageUpload(this,'#thirdImg')">
    <img id="thirdImg" class="img_style">
    <legend>Upload the figure 3</legend>
  </fieldset>
  <fieldset>
    <input type="file" onchange="imageUpload(this,'#fourthImg')">
    <img id="fourthImg" class="img_style">
    <legend>Upload the figure 4.</legend>
  </fieldset>


  <fieldset>
    <button onclick="clickPreview()">Click on the synthesis of</button>
    <button onclick="clickDownload()">Click on the download</button>
  </fieldset>
  <div id='base64ObjBox'>
    <p>Generate a Base64 file</p>
  </div>
  <div id='blobObjBox'>
    <p>Generate file</p>
  </div>
  <! -- <canvas id="myCanvas" width="200" height="200" style="border:1px solid #c3c3c3;" ></canvas> -->

</body>
<script>
  / * * *@description Merge images and return file methods *@param {Array} ImgsList List of images (urls or objects). Asterisks are mandatory@param {Boolean} IsFileObj Whether to return a file object. Default: false. Base64 * is returned@param {Number} CanvasWidth Generates the image width, default 200px *@param {Number} CanvasHeight Generates the image height. Default: 200px *@return  Merged image file, base64 or File */

  async function returnPicMerge(imgsList, isFileObj = false, canvasWidth = 200, canvasHeight = 200) {
    // The list of images is empty or not an array
    if (!Array.isArray(imgsList) || imgsList.length === 0) {
      return
    }
    // Initialize the list of images
    let imgEles = []
    if (typeof (imgsList[0= = =])'object') {
      // Image object list is used directly
      imgEles = imgsList
    } else {
      // Image link list needs to be processed into object list
      let imgSrcs = imgsList.map(item= > {
        let image = new Image()
        image.src = item + '? v=' + Math.random() // Handle the cache
        image.crossOrigin = The '*' // Support cross-domain images
        return new Promise(function (resolve, reject) {
          image.onload = function () {
            resolve(image)
          }
        // image.onerror = function() {
        // let defaultImg = new Image();
        // defaultImg.src = Config.publicTfsUrl + "/" + Config.defaultImg + '?v=' + Math.random();
        // defaultImg. CrossOrigin = '*' // support cross-domain images
        // defaultImg.onload = () => {
        // resolve(defaultImg);
        / /}
        });
      });
      imgEles = await Promise.all(imgSrcs);
    }

    // Initialize the image width, height and position coordinates
    let imgWidth = canvasWidth
    let imgHeight = canvasHeight
    let xCoordinate = 0
    let yCoordinate = 0

    // Create a canvas object
    let canvas = document.createElement('canvas');
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;

    let ctx = canvas.getContext("2d");

    // Fill the background color
    // ctx.fillStyle = "#87CEEB";
    // ctx.fillRect(0, 0, canvasWidth, canvasHeight);


    if (imgEles.length === 1) {
      // Draw a picture, a picture is covered
      ctx.drawImage(imgEles[0], xCoordinate, yCoordinate, imgWidth, imgHeight);
    } else if (imgEles.length === 2) {
      // The two pictures are side by side
      imgWidth = canvasWidth / 2
      imgHeight = canvasHeight/2
      yCoordinate = (canvasHeight - imgHeight) / 2
      imgEles.forEach((item, index) = > {
        ctx.drawImage(item, xCoordinate, yCoordinate, imgWidth, imgHeight);
        xCoordinate += imgWidth
      });
    } else if (imgEles.length === 3) {
      //
      imgWidth = canvasWidth / 2
      imgHeight = canvasHeight / 2
      xCoordinate = (canvasWidth - imgWidth) / 2
      imgEles.forEach((item, index) = > {
        if (index === 1) {
          yCoordinate += imgHeight
          xCoordinate = (canvasWidth - imgWidth * 2) / 2
        }
        ctx.drawImage(item, xCoordinate, yCoordinate, imgWidth, imgHeight);
        xCoordinate += imgWidth
      });
    } else if (imgEles.length === 4) {
      //
      imgWidth = canvasWidth / 2
      imgHeight = canvasHeight / 2
      imgEles.forEach((item, index) = > {
        if (index === 2) {
          yCoordinate += imgHeight
          xCoordinate = (canvasWidth - imgWidth * 2) / 2
        }
        ctx.drawImage(item, xCoordinate, yCoordinate, imgWidth, imgHeight);
        xCoordinate += imgWidth
      });
    }

    // Return the file
    if (isFileObj) {
      return new Promise(function (resolve, reject) {
        canvas.toBlob(function (blobObj) {
          resolve(blobObj)
        })
      })
    } else {
      return canvas.toDataURL('image/png')}}// Click upload image
  function imageUpload(imgFile, id) {
    let f = imgFile.files[0];// Get the uploaded image file
    let filereader = new FileReader();// Create an image object
    filereader.onload = function (event) {// The function to execute after the image is loaded
      let srcpath = event.target.result;// Here is the path to the image (the image will be converted to Base6)
      document.querySelector(id).setAttribute("src", srcpath);// Insert the obtained image into the corresponding image element
    };
    filereader.readAsDataURL(f);// Read the image (insert the image to read display)
  }
  function getImgSize(str) {
    // Get base64 image size, return KB number
    // var str = base64url.replace('data:image/jpeg; base64,', ''); // The format of the image is changed accordingly
    var strLength = str.length;
    var fileLength = parseInt(strLength - (strLength / 8) * 2);
    // Convert bytes to KB
    var size = "";
    size = (fileLength / 1024/1024).toFixed(2);
    
    return parseInt(size);

  }

  // Click preview
  async function clickPreview() {
    // Get the list of images
    let imgsList = Array.from(document.getElementsByClassName("img_style")).filter(item= > {
      if (item.src) {
        return item
      }
    });
    // If the user did not upload the file, initialize the assignment
    if (imgsList.length === 0) {
      imgsList = [
        'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3080163631, & FM = 26 & gp = 0. 1117627422 JPG'.'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F374%2F780%2F501%2F559858dc54b 34 a979c8816a8377fcf01.jpg&refer=http%3a%2f%2fyouimg1.c-ctrip.com & app = 2002 & size = f9999, 10000 & q = a80 & n = 0 & g = 0 n & FMT = jpeg? The SEC = 1 625888610&t=9a05b684a1f8426b8f3ccddc236ec271']},// Call the method to get base64
    let base64Obj = await returnPicMerge(imgsList)

    // Call the method to get the bloB
    let blobObj = await returnPicMerge(imgsList, true.200.200)

    var strLength = base64Obj.length;
    var fileLength = parseInt(strLength - (strLength / 8) * 2);
    console.log('base64Obj', base64Obj)
    console.log('base64Obj size', fileLength / 1024/1024)

    console.log('blobObj', blobObj)
    console.log('blobObj size', blobObj.size/1024/1024)
    

    let image1, image2
    let base64ObjBox = document.getElementById('base64ObjBox');
    let blobObjBox = document.getElementById('blobObjBox');
    // Create without image elements, update if there are
    if (document.getElementById('image1')) {
      image1 = document.getElementById('image1')
      image1.src = base64Obj
    } else {
      image1 = new Image()
      image1.src = base64Obj
      image1.setAttribute('id'.'image1');
      base64ObjBox.appendChild(image1);
    }
    if (document.getElementById('image2')) {
      image2 = document.getElementById('image2')
      image2.src = window.URL.createObjectURL(blobObj)
    } else {
      image2 = new Image()
      image2.src = window.URL.createObjectURL(blobObj)
      image2.setAttribute('id'.'image2'); blobObjBox.appendChild(image2); }}// Click download
  function clickDownload() {
    let img = document.getElementById("image1");
    let link = document.createElement('a');// Create an A tag
    link.download = 'my-image-name.jpg';// add a download attribute to the a tag. The value of the attribute (my-image-name.jpg) is the resultant file name
    link.href = img.src;// Assign the path to the href of the a tag
    link.click();// Simulate a TAB being clicked, so it can be downloaded
  }

</script>

</html>
Copy the code

conclusion

Returns the directory

Actually implementing some features by yourself is a pretty good experience. You can strengthen the familiarity with some functions and understanding of some apis, and you can also accumulate some spare code for yourself, so as not to waste time looking for information in case of encounter.

The road ahead is long, and I see no end.

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address

Document agreement



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.

Based on thegithub.com/danygitgitOn the creation of works.

Use rights other than those authorized by this License agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.