Home >Backend Development >PHP Tutorial >How to Convert a URL Image to a Base64 String?

How to Convert a URL Image to a Base64 String?

DDD
DDDOriginal
2024-12-19 12:16:15284browse

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 is determined in step 2.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn