How to implement downloading a PNG image with a click using Bootstrap 4 and JavaScript

Whenever I click on a picture, my goal is to immediately download it. The image is SVG, but there's an URL for a PNG version. It has been confirmed that the content disposition is set to attachment, and when the URL is directly copied, a download process initiates.

Bootstrap 4 is the framework in use.

The following function is being employed:

function downloadPNGImage(linkElement) {
    var myDiv = document.getElementById('download-area');
    var myImage = myDiv.children[0];
    let downloadLink = myImage.src + "&format=png";
    linkElement.setAttribute('download', downloadLink);
    linkElement.href = downloadLink;
}

The image itself is shown below:

<div class="col-lg-5 order-first order-md-last img-fluid" id="download-area">
    <img src="https://bananomonkeys.herokuapp.com/image?address=ban_1ttyqinz739g88tteqzyg3hwahg9oxbks8amsywqmim7j4afih7n9d1ssqjf&bg=t"
        class="loaded" id="generated-monKey" alt="" href="#" onclick="downloadPNGImage(this)" download>
</div>

Including "&format=png" should convert this URL from inline SVG to an attached PNG for downloading purposes. However, despite these efforts, the download feature does not seem to be functioning correctly.

Answer №1

Make a few changes to the function:

function updateImageLink(linkElement) {
    var imageContainer = document.getElementById('image-container');
    var mainImage = imageContainer.children[0];
    let newLink = mainImage.src + "&format=png";
    linkElement.setAttribute('download', newLink);
    linkElement.href = newLink;
    linkElement.click();
}

Adjust the onclick behavior:

onclick="updateImageLink(document.createElement('a'))"

Answer №2

If you're looking to enable downloading an image using the "download" attribute, it's important to note that it doesn't work directly on an <img> tag. A better approach would be to wrap your image within an <a> tag and apply the download attribute there instead. Also, ensure that in your JavaScript code, you are targeting the correct element for setting the .href property as simply adding it to an img tag won't have any effect.

Answer №3

When a user clicks on the link, a new window will open with the generated URL. The code implementation would be as follows:

function openDownloadLink(element) {
    var container = document.getElementById('download-section');
    var imageElement = container.children[0];
    let downloadURL = imageElement.src + "&format=png";
    window.open(downloadURL);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The `div` element automatically starts on a new line rather than expanding vertically

Check out my code here: http://jsfiddle.net/sfhs6ra1/ I'm facing an issue where I want the title of post #2 to be aligned next to the thumbnail image, taking up more vertical space instead of moving to a new line. Any suggestions on how I can achiev ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...

Stretching the Mantine Accordion Section

The Mantine accordion requires that its content be of type Accordion.Item, as indicated in the documentation for the children props. This means that even functions returning AccordionItem will not be recognized. Therefore, only AccordionItem(s) created in ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Adding an extra element to the <MuiThemeProvider /> causes the page to display as blank with no error notifications

After incorporating Material UI into my Meteor application via npm install --save material ui I successfully implemented the <Header /> component in my app.js file. However, when I try to add additional components, such as localhost:3000, all I see ...

Missing Personal toolbar button on Forge Viewer interface

After completing the tutorial for learning Autodesk Forge, I successfully linked my BIM 360 account to the Forge Viewer. My next goal is to add extensions and have a button on the toolbar that directs to these extensions. However, when following the exten ...

Sending parameters to a personalized Angular directive

I am currently facing a challenge in creating an Angular directive as I am unable to pass the necessary parameters for displaying it. The directive code looks like this: (function () { "use strict"; angular.module("customDirectives", []) .directive ...

Exploring the world of design with React JS and MUI's diverse styling options

Exploring the various styling options offered by MUI From useTheme, styled, makeStyles to other methods - what sets them apart and how do they differ in use cases? We're looking for a comprehensive breakdown of their unique features, practical appli ...

Arranging data in a JSON array while handling null values in JavaScript

Here is my JSON array: var jData = [ {id: 1, parent: null}, {id: 2, parent: null}, {id: 3, parent: 1}, {id: 4, parent: 2}, {id: 5, parent: 2}, {id: 6, parent: 1}]; I would like to sort it in the following order (first by id then by parent): [ {id: 1 ...

Incorporating AngularJS into your current JavaScript code base

We have a JavaScipt project underway that could greatly benefit from incorporating AngularJS. However, due to the size of the project, completely rewriting it in Angular is not feasible. Does anyone have any suggestions or tips on how to integrate Angula ...

Deciphering JSON data in an Express.js application

In a Node.js/Express.js application, an API call is made to another server which responds with JSON data. However, the received JSON response is not being properly parsed into new variables. What specific modifications should be applied to the code below i ...

The concept of an HTML pop-up message that hovers above the content

While working on my HTML form, I encountered an issue regarding the display of a warning message notifying users about the caps lock being on. Currently, the warning is shown correctly in a div located to the right of the text box. However, this div's ...

Integration issue: React.js is failing to render within a Django project

I have been working on a project where React is not rendering anything on Django localhost. index.html <!DOCTYPE html> <html lang="en"> <head></head> <body> <div id="App"> <!---all will b ...

Adjust and position any svg element to fit the entire viewport

Forgive me for being just another person to ask this question. Despite my efforts, I have yet to find a solution. I am trying to resize "any" svg to fit the entire viewport, centered. Take for example this svg element: <svg baseProfile="full& ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

The scrolling feature in IE 7 with IE 7 standard does not respond to the jquery scroll event, whereas it functions properly in IE8 and IE

I have included an example below which consists of a terms div that contains some terms and conditions as its content. The checkbox is enabled when the user scrolls to the bottom of the div. However, this functionality seems to be not working properly in I ...

What is the best way to incorporate ng-pluralize into a loop and access the count value?

Is there a way to access the iterator in the count attribute when using ng-pluralize within a loop? <option ng-repeat="i in [1,2,3,4,5]" value="{{ i }}"> {{ i }} star<ng-pluralize count="i" when="{'1': '', 'other': ...

How can I make the fullcalendar 'moreLink' popover stay open when clicking outside?

Currently, I am working with FullCalendar v6 on nextjs. One built-in feature that caught my attention is the event popover that appears when there are too many events, accessible by clicking "more." However, I am facing a challenge in preventing this pop ...

What is the best technique to incorporate dark/light mode in Bootstrap 5?

Is it best to introduce themes such as dark and light themes in Bootstrap 5 using CSS/SCSS, JavaScript, or a combination of both? Should we create a separate CSS file like dark.css to overwrite classes? Or should we use JavaScript to switch classes like ...