'jQuery Save Image Onclick

On my website I have a jQuery script that, if the download button is clicked it will open the image that you want in new window.

My question is, how can I make this script when you click the button the image will save automatically and not open in a new window.

My code :

<script type="text/javascript">
        $(document).ready(function (){
            $('#download-btn').click(function(){
                var size = $('#size').val();                
                window.open(size);
            });
        })
    </script>


Solution 1:[1]

First I try jqueryfiledonwloader but not work on image file,after a some searching I found below solution,This work for me charmly,try this

 <script type="text/javascript">
        $(document).ready(function (){
            $('#download-btn').click(function(){
     var link = document.createElement('a');
                  link.href = '/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg';  // use realtive url 
                  link.download = 'MyToy.jpeg';
                  document.body.appendChild(link);
                  link.click();     
           });
        })
    </script>

Solution 2:[2]

<button class="btn btn-success" style="width: 250px;" data-image="/media/result/online_resultjpg_Page68.jpg" data-exam="GMO" data-roll="110211" onclick="downloadCertificate(this);" >Download Certificate</button>

<script type="text/javascript">
function downloadCertificate(obj){
    var link = document.createElement('a');
    const image = $(obj).data("image");
    const img_ext = image.split(".");
    const ext = img_ext[img_ext.length - 1];
    link.href = image;
    link.download = $(obj).data("exam") + "_" + $(obj).data("roll") + ext;
    document.body.appendChild(link);
    link.click();
}
</script>

Solution 3:[3]

Yuseferi script solution could be transformed into a simple anchor tag we put before the closing of the #download-btn one:

<a href='/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'
   download='MyToy.jpeg'>MyToy.jpeg</a>

By the way, download is a standard HTML5 anchor tag (MDN) attribute and, in script, it is flagged "experimental": maybe because of unwanted side effect. Still Yuseferi solution should be full proof.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yuseferi
Solution 2 vinod kumar
Solution 3