3

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?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Rajesh Rs
  • 1,301
  • 5
  • 24
  • 48
  • Interesting... I know of PHP image manipulation libraries, but I've never seen one in JavaScript. Be curious to see if such a thing exists, too. – Greg Pettit Dec 06 '11 at 05:24
  • As Javascript is clientside, you can't save anything like this. You'll need to do some work in php or flash too. – OptimusCrime Dec 06 '11 at 10:03
  • OptimusCrime has a good point :). Image files can be stored on the client (e.g. using localstorage), but definitely not saved to a file somewhere on the disk automatically - user will have to do the saving manually. – kubetz Dec 06 '11 at 10:26

1 Answers1

3

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).

Community
  • 1
  • 1
kubetz
  • 8,485
  • 1
  • 22
  • 27