Home >Backend Development >PHP Problem >How to convert images to base64 encoding in php

How to convert images to base64 encoding in php

王林
王林Original
2021-09-18 15:10:036346browse

The method for php to convert images to base64 encoding is: [

How to convert images to base64 encoding in php

The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.

Introducing how to convert images Before converting to base64 encoding, let’s briefly talk about what base64 encoding is. Maybe many friends don’t know much about it. Let’s take a look at it together.

base64 is the most common one on the current network One of the encoding methods for transmitting 8Bit byte codes. The main function of base64 is not to encrypt. Its main function is to convert certain binary numbers into ordinary characters for network transmission. Since these binary characters are controlled in the transmission protocol Characters cannot be transmitted directly, so they need to be converted. Although images can be transmitted directly, we can also turn them into strings and put them directly in the source code, without the browser needing to download the source code after reading it from the server.

So how do we use PHP to base64 decode and output images? Let’s take a look at the implementation code:

<?php
$img = &#39;test.jpg&#39;;
$base64_img = base64EncodeImage($img);
  
echo &#39;<img src="&#39; . $base64_img . &#39;" />&#39;;
  
function base64EncodeImage ($image_file) {
  $base64_image = &#39;&#39;;
  $image_info = getimagesize($image_file);
  $image_data = fread(fopen($image_file, &#39;r&#39;), filesize($image_file));
  $base64_image = &#39;data:&#39; . $image_info[&#39;mime&#39;] . &#39;;base64,&#39; . chunk_split(base64_encode($image_data));
  return $base64_image;
}
?>

Summary:

The base64 encoding obtained after conversion through the above method Strings can be stored in the database, and can be read directly from the database when needed to reduce the number of requests when accessing images. In addition, this method has been included in the global function library of MiniFramework.

Recommended learning: phptraining

The above is the detailed content of How to convert images to base64 encoding 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