Home >Backend Development >PHP Tutorial >How Can I Convert Images to Base64 Encoding for Web Embedding?
Converting Images to Base64 Encoding: A Step-by-Step Guide
Converting images to Base64 encoding is a convenient way to embed images into HTML documents or other digital formats. Here's how to do it:
For Images from a URL:
To convert an image from a URL to Base64 encoding, use the following PHP script:
$url = 'https://example.com/image.png'; $type = pathinfo(basename($url), PATHINFO_EXTENSION); $data = file_get_contents($url); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
This code retrieves the image from the specified URL, determines its file type, and then converts it to Base64 encoding. The resulting string can be used as an inline image source in HTML or other formats.
Usage:
Once the image is converted to Base64, you can embed it into HTML using the following syntax:
<img src="<?php echo $base64; ?>" alt="My Image">
This code will display the converted image in your web page.
The above is the detailed content of How Can I Convert Images to Base64 Encoding for Web Embedding?. For more information, please follow other related articles on the PHP Chinese website!