简体   繁体   English

使用 JavaScript 下载图像

[英]Image download using JavaScript

I'm working on JavaScript code to upload, preview, and download image.我正在使用 JavaScript 代码来上传、预览和下载图像。 currently I have done upload and preview code.目前我已经完成了上传和预览代码。 after that, How to download it?之后,如何下载呢?

    <section class="upload" id="upload">
            <h3>UPLOAD</h3>
          
          <div class="container">
            <div class="row">
              
              <canvas id="c" class="p-3" >Here's the canvas.</canvas>
              <br>
              <input type="file" id="infile" accept = "image/*" onchange="handleFiles(this.files)">
              <p><img id="output" /></p>
              <button onclick="blurimg()" class="btnbl">Blur Image</button>
              <br>
             </div>
            </div>
      
    </section>
     //Canvas creating with image
        document.getElementById('infile').onchange = function(e) {
          var img = new Image();
          img.onload = draw;
          img.onerror = failed;
          img.src = URL.createObjectURL(this.files[0]);
        };
        function draw() {
          var canvas = document.getElementById('c');
          canvas.width = this.width;
          canvas.height = this.height;
          var ctx = canvas.getContext('2d');
          ctx.drawImage(this, 0,0);
        }
        function failed() {
          console.error("The provided file couldn't be loaded as an Image media");
        }

you can do it in HTML check this example: https://www.w3schools.com/tags/att_a_download.asp你可以在HTML检查这个例子: https://www.w3schools.com/tags/att_a_download.asp

Untested but it would be something in the lines of:未经测试,但它会是这样的:

async function downloadCanvas () {
  const type = 'image/jpeg'
  const quality = 1
  const blob = await new Promise(rs => canvas.toBlob(rs, type, quality)
  const link = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  a.download = 'cat.jpg'
  a.click()
}

If you want and support newer browser, then you can use bitmap = await createImageBitmap(file) instead of painting a <img>如果您想要并支持更新的浏览器,那么您可以使用bitmap = await createImageBitmap(file)而不是绘制<img>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM