Converting image files to png and uploading to server

I need to append two lines of text below jpg photos.
The photos are resized to fit within defined width and heights.
The html

<!DOCTYPE HTML>
<html>
<head>
	<script defer src="./album_dev.js"></script>
</head>
<body>
<div id="dlgAnchor"></div>
<!--multiple is set to allow multiple files to be selected-->
<input type="file" multiple onchange="readInFiles()"><br>

<canvas id="canvas"></canvas>;

<svg id="svgA"  width="800" height="900" xmlns="http://www.w3.org/2000/svg">
	<svg id="svgB" x="0" y="0" width="800" height="900"  preserveAspectRatio="xMinYMin meet">
		<image id = "svgImg" ></image>
		<rect id="svg_rect" x="0" y="700" width="800" height= 32 style="fill:cyan;" />
		<text id="titleTxt" x="20" y="480" style="fill:black;"></text>
		<text id="artistTxt" x="20" y="784" style="fill:black;"></text>
	</svg>
</svg>

</body>
</html>


I set the image element’s href to a new image object and then add the text to the text elements.
The svg element is drawn into the canvas element and then converted to a png image
and posted to a php script where it is saved.
It works brilliantly for a single file,
But when multiple files are inputted the output uses the dimensions of the last image processed.
In the exportAsPng function the inputs are the svg element and the file name
The relevant js function.

const exportAsPng = (svgElement, name) => {
	let {width, height} = svgElement.getBBox();
		let data = svgElement.outerHTML;
	   let canvas = $id('canvas');
	   let context = canvas.getContext('2d');
	   canvas.width = width;
	   canvas.height = height;

		console.log("The canvas  width and height for " +  name + " is: " + width + " / " + height);

		let DOMURL = window.URL || window.webkitURL || window;
	   let img = new Image();
		let svg = new Blob([data], {type: 'image/svg+xml'});
		let url = DOMURL.createObjectURL(svg);
		img.src = url;
		img.onload =  function () {
			context.drawImage(img, 0, 0);
			DOMURL.revokeObjectURL(url);
			let png_img = canvas.toDataURL().replace(/^data:image\/png;base64,/, "");
			let fname = name.replace(/jpg$/,"png");

			console.log("The canvas  width and height for " +  name + " in the img.onload function   is: " + canvas.width + " / " + canvas.height);

			POST({cmd: "savePNG", path: "images_png/",fname: fname, data: png_img});
		}
}

The POST function is my abstracted way of sending POST requests.
The console log has all the first log calls and then all the latter log calls.
The img.onload function is invoked after every image file has been written to the canvas element
and photos which have smaller width or heights show content from other images or if they have larger widths or heights they are truncated.

The img.onload function is using the correct image data but the wrong image dimensions.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.