Home > php教程 > PHP开发 > How to use PHP to convert images into base64 encoding

How to use PHP to convert images into base64 encoding

高洛峰
Release: 2016-12-27 09:48:50
Original
1624 people have browsed it

Let’s first talk about why we base64 encode images

base64 is one of the most common encoding methods for transmitting 8-bit byte code on the current network. Base64 is not mainly for encryption. Its main purpose is to convert certain binary numbers into ordinary characters for network transmission. Since these binary characters are control characters in the transmission protocol and cannot be transmitted directly, they need to be converted. Although the image may be transmitted directly, we can also turn it into a string and put it directly in the source code, without requiring the browser to download it from the server after reading the source code.

How to use PHP to base64 decode and output images

<?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;
}
?>
Copy after login

Summary

The base64 encoded string obtained after conversion through the above method can be stored in the database when needed It can be read directly from the database to reduce the number of requests when accessing images. This method has been included in MiniFramework's global function library. The above is the entire content of this article. I hope that the content of this article can bring some help to everyone's study or work. Thank you for your support to the PHP Chinese website.

For more related articles on how to use PHP to convert images into base64 encoding, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template