29

我的目标是让 iPad 上的用户将图像加载到画布中,然后在离线时获取 base 64 编码的所述图像

JSFiddle

JSFiddle

代码

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="../js/libs/jquery-1.7.1.min.js"></script>
    <script>
      $(document).ready(function(){ 
        //Get the canvas
        var canvas = document.getElementById('testCanvas');
        var context = canvas.getContext('2d');   

        $("#testButton").click(function(){
          var base_image = new Image();

          base_image.src = $("#testImg").val();
          //base_image.src = '1.jpg';

          //When the image loads
          $(base_image).load(function(){
            //Resize canvas for image
            $("#testCanvas").attr({
              width: base_image.width,
              height: base_image.height
            });

            //Draw image on canvas
            context.drawImage(base_image, 0, 0);

            //Get base64 encoded image
            var imageString = canvas.toDataURL("image/jpeg");
            $("#imageString").val(imageString);

            //alert($("#imageString").val().length);
            $("#imageOutput").attr("src", imageString);
          });//image load
        });//Test Button Click
      });//doc ready
    </script>
  </head>

  <body>
    <form>
      <input type="file" name="testImg" id="testImg" />
    </form>
    <button id="testButton">Test</button>
    <canvas id="testCanvas" style="border: 1px solid black;">Your Browser does not support canvas</canvas>
    <br />
    <fieldset>
      <legend>Image Data</legend>
      <textarea id="imageString"></textarea>

      <img id="imageOutput" src="" />
    </fieldset>
  </body>
</html>

我知道图像实际上并没有从 加载<input type='file' />,但我认为值得一试。在 Chrome 控制台中,我得到:

不允许加载本地资源

有什么方法可以让我将 iPad 中的图像放入画布元素中?

非常感谢任何帮助、提示或建议!谢谢!

4

2 回答 2

72

我有一个功能正常的小提琴(基于此答案的先前工作),它演示了如何使用文件输入上传图像,将其放置在画布中,然后读回 base64 数据 URL。

简而言之,您应该:

  1. 使用File API读取图像(您可以在onchange输入元素的侦听器中执行此操作):
var file = input.files[0];
var fr = new FileReader();
fr.onload = createImage;   // onload fires after reading is complete
fr.readAsDataURL(file);    // begin reading
  1. 在 FileReader 的onload回调(此处,createImage)中,读取resultFileReader 的(此处,fr.result)。那是您的图像数据 URL!

可选步骤(仅当您计划在画布上操作图像时才需要):

  1. 在 FileReader 的onload回调(此处为createImage)中,创建一个新Image对象并将其设置srcresultFileReader:
img = new Image();
img.onload = imageLoaded;
img.src = fr.result;
  1. 最后,在 Image 的onload回调中,将其绘制到画布上,然后用于canvas.toDataUrl数据:
canvas.width = img.width;      // set canvas size big enough for the image
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);         // draw the image

// do some manipulations...

canvas.toDataURL("image/png");  // get the data URL
于 2012-12-18T18:25:30.567 回答
1

输入文件,文件上传后使用javascript减小文件大小并再次传递输入文件值。

const input = document.getElementById("img-input");
input.onchange = function (ev) {
  const file    = ev.target.files[0]; // get the file
  const blobURL = URL.createObjectURL(file);
  const img     = new Image();
  img.src       = blobURL;

  img.onerror = function () {
    URL.revokeObjectURL(this.src);
    // Handle the failure properly
    console.log("Cannot load image");
  };

  img.onload = function () {
    URL.revokeObjectURL(this.src);
    const mime_type = "image/jpeg";
    const quality = qualityRate(file.size);
    const canvas  = document.createElement("canvas");
    canvas.width  = img.width;
    canvas.height = img.height;
    const ctx     = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);

    document.getElementById("root").append(canvas);
    //let data = canvas.toDataURL(mime_type,quality);
    //downloadURI(data, 'stage.jpg');

    canvas.toBlob(blob => {
        let localfile = new File([blob], 'a.jpg',{type:"image/jpeg", lastModified:new Date().getTime()}, 'utf-8');
        let container = new DataTransfer();
        container.items.add(localfile);
        document.querySelector('#img-input').files = container.files;
    },mime_type,quality);
  };
};

function qualityRate(fileSize){
    let QUALITY = 0.5;
    
    if(1000000 > fileSize){
        QUALITY = 0.5;
    }
    else if(3000000 > fileSize){
        QUALITY = 0.7;
    }
    else if(5000000 > fileSize){
        QUALITY = 0.5;
    }
    else if(10000000 > fileSize){
        QUALITY = 0.9;
    }
    else{
        QUALITY = 0.1;
    }
    console.log(QUALITY);
    return QUALITY;
}

function downloadURI(uri, name) {
    var link = document.createElement('a');
    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    delete link;
}
<form action="test.php" method="post" enctype="multipart/form-data">
    <input id="img-input" type="file" name="fileTest" accept="image/*" />
    <input type="submit" name="submit" value="aa">
</form>
<div id="root" style=" display: none; "></div>

于 2022-02-24T11:03:22.920 回答