How to embed a small image on top of another image and save it using JavaScript?

橙三吉。 提交于 2019-12-22 09:55:12

问题


I have a large image tif format and two small images.

What I wanted to achieve is that I want to embed either of the two small images on top of a large image and save it using JavaScript.

 <html>
    <body>
        <img src="largeimg" />
        <p>Select the image to embed on the large image</p>
        <img src="smallimg1" />
        <img src="smallimg2" />
    </body>
 </html>

Is there any way to achieve the above using javascript?


回答1:


If the images are on the same origin the it is possible to use canvas.

  • draw images to canvas
  • call canvas.toDataURL() to retrieve the image data
  • create img element and append data to it

Example:

HTML:

<img id="main" src="image1" />
<img class="small" src="image2" data-posx="0" data-posy="0" />
<img class="small" src="image3" data-posx="50" data-posy="50" />
<div id="result"></div>

JavaScript:

function process(main, rest) {
  var canvas = document.createElement("canvas");
  canvas.width = main.width;
  canvas.height = main.height;

  var ctx = canvas.getContext("2d");
  ctx.drawImage(main, 0, 0);

  for (var i = 0; i < rest.length; i++) {
    var img = rest[i];
    ctx.drawImage(img, img.getAttribute("data-posx"), img.getAttribute("data-posy"));
  }

  return canvas.toDataURL("image/png");
}

var img = document.createElement("img");
img.src = process(document.getElementById("main"),  document.getElementsByClassName("small"));
document.getElementById("result").appendChild(img); 

If you want to write the image on [0, 0] coordinates then you don't have to use data- attributes, of course. Problem with this approach is that if the files are hosted on different origin then toDataURL will throw security error.

Based on: https://stackoverflow.com/a/934925/1011582

Note: I would like to link jsfiddle or jsbin example but because of the same origin policy I cannot create any reasonably looking example. Any ideas?

THIS is the best example I was able to get (tested with Chrome & FF).



来源:https://stackoverflow.com/questions/8395613/how-to-embed-a-small-image-on-top-of-another-image-and-save-it-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!