Home >Backend Development >PHP Tutorial >How to Convert a URL Image to a Base64 String?
Convert an Image to Base64 Encoding from a URL
To transform an image from a URL into Base64 encoding, follow these steps:
1. Fetch Image Data from URL:
Retrieve the image data using the file_get_contents function, providing the URL as an argument.
2. Determine Image Type:
Use pathinfo with the PATHINFO_EXTENSION option to extract the file extension, which indicates the image type (e.g., PNG, JPEG).
3. Convert to Base64 String:
Utilize the base64_encode function to convert the raw image data into a Base64-encoded string.
4. Stitch Base64 Prefix:
Prepend the Base64-encoded string with a data URI prefix, which consists of the following format:
where
Example Code:
The above is the detailed content of How to Convert a URL Image to a Base64 String?. For more information, please follow other related articles on the PHP Chinese website!