Home >Backend Development >PHP Tutorial >How to convert image to base64 encoding format in PHP

How to convert image to base64 encoding format in PHP

藏色散人
藏色散人Original
2019-01-24 14:08:597353browse

The base64_encode() function is a built-in function in PHP that is used to convert any data to base64 encoding. In order to convert an image to base64 encoding, you first need to get the contents of the file, which can be done through PHP's file_get_contents() function. This raw data is then passed to the base64_encode() function for encoding.

Required functions:

base64_encode() function is a built-in function in PHP for encoding data using MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode strings in base64. The base64_encoded data takes up 33% more space than the original data.

file_get_contents() function is also a built-in function in PHP for reading files into strings. This function uses server-supported memory mapping technology, which improves performance and makes it the preferred method for reading file contents.

The input image is as follows:

How to convert image to base64 encoding format in PHP

The PHP code program is as follows:

<?php

// 获取图像并转换为字符串
$img = file_get_contents(&#39;img/001.jpg&#39;);

// 将图像字符串数据编码为base64
$data = base64_encode($img);

// 显示输出
echo $data;

Output :

/9j/4RUURXhpZgAASUkqAAgAAAAMAAABAwABAAAAgAIAAAEBAwABAAAAkAEAAAIBAwADAAAAng
AAAAYBAwABAAAAAgAAABIBAwABAAAAAQAAABUBAwABAAAAAwAAABoBBQABAAAApAAAABsBBQAB
AAAArAAAACgBAwABAAAAAgAAADEBAgAeAAAAtAAAADIBAgAUAAAA0gAAAGmHBAABAAAA6AAAACA
...
p2wFEq1LzJPMknzajI0ArU1yGkc+ITj2dJPPrPo+H/0DQ4y9NQ/Zgioyy+XLyk5cvqxxy5+b/9k=

Recommended study: "PHP Tutorial"

This article is an introduction to how to convert images to base64 encoding format in PHP. It is simple and easy to understand. I hope Help those in need!

The above is the detailed content of How to convert image to base64 encoding format in PHP. 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