An Introduction to Image-Size APIs
Image-size APIs offer a myriad of functionalities that allow developers to handle image properties programmatically. These APIs can fetch image dimensions, resize images, and perform various other manipulations efficiently. Here, we delve into dozens of useful APIs with accompanying code snippets.
Fetching Image Dimensions
One of the basic functions of image-size APIs is to fetch the dimensions of an image. This can be pivotal when working with responsive designs and media queries.
const img = new Image(); img.onload = function() { console.log('Width: ' + this.width + 'px, Height: ' + this.height + 'px'); }; img.src = 'image-url.jpg';
Resizing Images
Another critical functionality is resizing images. This can be done using offscreen canvases in the browser.
const resizeImage = (imgSrc, newWidth, newHeight) => { const img = new Image(); img.src = imgSrc; img.onload = function() { const canvas = document.createElement('canvas'); canvas.width = newWidth; canvas.height = newHeight; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, newWidth, newHeight); document.body.appendChild(canvas); }; }; resizeImage('image-url.jpg', 300, 150);
Converting Image Formats
Conversion between different image formats (e.g., JPG to PNG) is another common task handled by image-size APIs.
const convertImageFormat = (imgSrc, format) => { const img = new Image(); img.src = imgSrc; img.onload = function() { const canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); canvas.toDataURL('image/' + format); }; }; convertImageFormat('image-url.jpg', 'png');
App Example
Here’s an example of a simple web application that utilizes the aforementioned APIs.
<!DOCTYPE html> <html> <head> <title>Image Size API Demo</title> </head> <body> <img id="myImage" src="image-url.jpg" alt="Demo Image"> <button onclick="resizeImage('image-url.jpg', 300, 150)">Resize Image</button> <script> const resizeImage = (imgSrc, newWidth, newHeight) => { const img = new Image(); img.src = imgSrc; img.onload = function() { const canvas = document.createElement('canvas'); canvas.width = newWidth; canvas.height = newHeight; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, newWidth, newHeight); document.body.appendChild(canvas); }; }; document.getElementById('myImage').onload = function() { console.log('Original Width: ' + this.width + 'px, Original Height: ' + this.height + 'px'); }; </script> </body> </html>
By utilizing these APIs, developers can efficiently manage image properties and optimize content for SEO purposes.
Hash: c79ac25ef4ae39e4c10eaeed5a1986960f0cc67da51ca9ce008144ce15fcf53e