PHP source code to convert images into data/base64 data stream detailed explanation

墨辰丷
Release: 2023-03-28 13:30:01
Original
2227 people have browsed it

In website development, we can see that some websites convert images into base64 data streams. This has two advantages. One is to reduce server http requests, and the other is to store images as strings in the database. , that is, the picture can be read directly from the database, so how does PHP convert the picture into a data/base64 string? , Friends in need can refer to

php source code to convert images into data/base64 data stream

Here we share a method to convert images into base64 encoding format :

<?php
$img = &#39;test.jpg&#39;;
$base64_img = base64EncodeImage($img);
 
echo &#39;<img src="&#39; . $base64_img . &#39;" />&#39;;
/* 作者:http://www.manongjc.com */
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

The base64 encoded string converted by the above method can be stored in the database and can be read directly from the database when needed, reducing The number of requests when accessing the image.

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations: The difference between static properties and static methods in

php

PHP implementation method of adding elements to the head and tail of an array

php Implementation method of loop traversal of one-dimensional array

The above is the detailed content of PHP source code to convert images into data/base64 data stream detailed explanation. For more information, please follow other related articles on 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!