Using a solution in this question by brunobar79. My problem is that I am getting the following error;
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
My JS;
<script type="text/javascript">
var jic = {
compress: function(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
};
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality/100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},
}
function myFunction(){
var source_img = document.getElementById("source_img"),
target_img = document.getElementById("target_img");
var quality = 80,
output_format = 'jpg';
target_img.src = jic.compress(source_img,quality,output_format).src;
console.log("I am a myFunction!");
};
</script>
snippet of my HTML;
<form> <img src="" id="target_img"> </form>
<button onclick="myFunction()" >compress</button>
Another developer has added the HTML/Python code hence not really sure what to add here from that. The <form>
has source_img
defined as an ID in it.
The client's requirement is that when an image, once selected, should get compressed and then placed in <img>
after the compress button is clicked.This is the first time I am using image compression using JS in the client-side and I am considerably new to JS. Please advise.