Get image html javascript
Last updated: Apr 30, 2023
Reading time · 5 min
# Table of Contents
# Download an image by using a simple link
If you need to download an image that is stored on the same domain or stored locally, you can use a simple a element that has the download attribute set.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div>bobbyhadz.comdiv> br /> a href="house.png" download>Download imagea> body> html>
The example above assumes that you have a house.png image located in the same directory as your index.html file.
However, note that this approach only works when the href attribute of the a element points to:
- a URL of an image that is hosted on the same domain, e.g. http://localhost:3000/house.png .
- a local image, e.g. house.png .
Copied!a href="house.png" download>Download imagea>
Make sure to specify the extension (e.g. .png ).
If specifying a URL, make sure to include the protocol ( http:// or https:// ).
You can also wrap the a element in a button and style it.
Copied!button> a href="house.png" download>Download imagea> button>
The image is downloaded when the user clicks on the button.
The download attribute causes the browser to treat the linked URL as a download.
You can also set the download attribute to a string to specify the name the downloaded image should have on the user’s file system.
Copied!a href="house.png" download="my-file.png">Download imagea>
However, it is not guaranteed that the browser will use the specified image. Some browsers might use the name of the image as stored on your server’s file system.
In this case, you can use the fetch method as shown in the next subheading.
# How to Download Images using JavaScript
To download an image using JavaScript:
- Use the fetch() method to get a Blob object.
- Use the createObjectURL method to get a string containing the image’s URL.
- Create an anchor element and use it to download the image.
Here is the HTML for the example.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> body margin: 100px; > style> head> body> div>bobbyhadz.comdiv> br /> button id="btn">Download imagebutton> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!async function downloadImage( imageSrc, nameOfDownload = 'my-image.png', ) const response = await fetch(imageSrc); const blobImage = await response.blob(); const href = URL.createObjectURL(blobImage); const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = nameOfDownload; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); > const btn = document.getElementById('btn'); btn.addEventListener('click', () => downloadImage( 'http://localhost:3000/house.png', 'my-image.png', ) .then(() => console.log('The image has been downloaded'); >) .catch(err => console.log('Error downloading image: ', err); >); >);
The downloadImage function takes care of downloading the image when the user clicks on the button element.
The function takes the source of the image and the name of the download as parameters.
The imageSrc parameter could be a complete URL that points to an image:
Or it could be an image from the local file system, for example:
- house.png
- or images/house.png (a house.png image located in an images/ directory)
- or ../images/house.png (an images/ folder that is located one directory up)
Copied!async function downloadImage( imageSrc, nameOfDownload = 'my-image.png', ) >
The nameOfDownload parameter is used to set the name of the downloaded file on the user’s file system.
Copied!async function downloadImage( imageSrc, nameOfDownload = 'my-image.png', ) const response = await fetch(imageSrc); const blobImage = await response.blob(); const href = URL.createObjectURL(blobImage); const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.download = nameOfDownload; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); window.URL.revokeObjectURL(href); >
The downloadImage function does the following things:
- It uses the built-in fetch() method to fetch the image from a URL (or from the local file system).
- It uses the blob() method of the Response object to get a Blob object (a file-like object of immutable, raw data).
- It uses the createObjectURL method to create an object URL that can be used to reference the contents of the image.
- It creates an a (anchor) element and sets its href attribute to the object URL and its download attribute to the name the downloaded image should have on the user’s file system.
- It appends the anchor element to the body and simulates a click to initiate the download.
- It removes the link element from the body and revokes the URL after the image has been downloaded.
Make sure to update the parameters in the call to the function.
The example assumes that you are downloading a house.png image that is accessible at http:/localhost:3000/house.png .
You can either specify a complete URL to an image (including the protocol http:// or https:// ) and the extension ( .png , .jpg , etc) or a path to a local image (e.g. house.png ).
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', () => downloadImage( 'http://localhost:3000/house.png', 'my-image.png', ) .then(() => console.log('The image has been downloaded'); >) .catch(err => console.log('Error downloading image: ', err); >); >);
If you try to download an image from a remote URL, the server that stores the image has to send CORS headers that allow your browser to download the image.
If you get a TypeError: Failed to fetch and CORS error, click on the link and follow the instructions.
CORS is a mechanism that allows a server to use a combination of HTTP headers to indicate from which domains, other than its own, it receives requests.
By default, a server can only be accessed from its own domain unless the correct Access-Control-Allow-* headers are set.
If you need to download a file or an image using axios , check out the following article.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- How to fetch Data on Button click in React
- TypeError: Failed to fetch and CORS in JavaScript [Solved]
- fetch() returns empty Response Body in JavaScript [Solved]
- How to Use an Image as a Link in React.js
- Import and use an Image in a React component
- Convert an HTML table to JSON and export it to a file in JS
- Refresh an image with a new one at the same URL using JS
- Convert Bytes to KB, MB, GB or TB using JavaScript
- console.log() not working in JavaScript & Node.js [Solved]
- How to convert a Blob to an ArrayBuffer in JavaScript
- How to save an image to localStorage using JavaScript
- How to Preview an image before uploading in JavaScript
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
HTML DOM Image Object
You can access an element by using getElementById():
Example
Tip: You can also access an element by using the images collection.
Create an Image Object
You can create an element by using the document.createElement() method:
Example
Image Object Properties
Property | Description |
---|---|
align | Not supported in HTML5. Use style.cssFloat instead. Sets or returns the value of the align attribute of an image |
alt | Sets or returns the value of the alt attribute of an image |
border | Not supported in HTML5. Use style.border instead. Sets or returns the value of the border attribute of an image |
complete | Returns whether or not the browser is finished loading an image |
crossOrigin | Sets or returns the CORS settings of an image |
height | Sets or returns the value of the height attribute of an image |
hspace | Not supported in HTML5. Use style.margin instead. Sets or returns the value of the hspace attribute of an image |
isMap | Sets or returns whether an image should be part of a server-side image-map, or not |
longDesc | Not supported in HTML5. Sets or returns the value of the longdesc attribute of an image |
lowsrc | Not supported in HTML5. Sets or returns a URL to a low-resolution version of an image |
name | Not supported in HTML5. Use id instead. Sets or returns the value of the name attribute of an image |
naturalHeight | Returns the original height of an image |
naturalWidth | Returns the original width of an image |
src | Sets or returns the value of the src attribute of an image |
useMap | Sets or returns the value of the usemap attribute of an image |
vspace | Not supported in HTML5. Use style.margin instead. Sets or returns the value of the vspace attribute of an image |
width | Sets or returns the value of the width attribute of an image |
Standard Properties and Events
The Image object also supports the standard properties and events.