How to convert images using php base64

藏色散人
Release: 2023-03-07 21:06:01
Original
6089 people have browsed it

php Base64 method of converting images: First create a PHP sample file; then use the "file_put_contents('./test_base2.jpg', base64_decode($base64));" method to convert the base64 string into an image. Can.

How to convert images using php base64

The operating environment of this tutorial: Windows 7 system, PHP version 5.6. This method is suitable for all brands of computers.

Recommended: "PHP Video Tutorial"

PHP images and base64 conversion

PHP Convert images to base64 characters String format:

<?php
//Filetype: JPEG,PNG,GIF 
 
$file = "encode.jpg"; //$file:图片地址
if($fp = fopen($file,"rb", 0)) 
{ 
    $gambar = fread($fp,filesize($file)); 
    fclose($fp); 
 
    //获取图片base64 
    $base64 = chunk_split(base64_encode($gambar)); 
    // 输出
    $encode = &#39;<img src="data:image/jpg/png/gif;base64,&#39; . $base64 .&#39;" >&#39;; 
    echo $encode; 
}     
?>
Copy after login

Convert base64 string to image:

//第一个参数图片保存路径以及图片名称 需注意图片后缀 linux请注意文件权限
//第二个参数为图片的base64字符串  ps:下方会贴出图片base64的格式 以及注意事项
 
file_put_contents(&#39;./test_base2.jpg&#39;, base64_decode($base64));
Copy after login

Detailed explanation of image base64 string:

//读取图片数据
$gambar = fread($fp,filesize($file)); 
//获取图片base64 
$base64 = chunk_split(base64_encode($gambar));
 
 
//$gambar->读取的是图片的数据流
//$base64->将图片数据流转换为base64
Copy after login

The base64 string format of the image obtained at this time is: ps: The data obtained for each image is different, here is just an example

/9j/4AAQSkZJRgABAQEAkACQAAD/4QC....此处省略N多字符串......KKKAP/2Q==
Copy after login

starts with data, which is the image header information added to display the image. So we only use the data of `$base64`

data:image/jpg/png/gif;base64,/9j/4AAQSkZJRgABAQEAkACQAAD/4QC....此处省略N多字符串......KKKAP/2Q==
Copy after login

In addition, we can also append some strings or other data to the picture and save it as a picture

$base64 = chunk_split(base64_encode($gambar) .&#39;#&#39;. base64_encode(&#39;举个例子&#39;)); 
//将需要追加的数据也转换为base64格式,注意 【#】符号
Copy after login

More programming related knowledge , please visit: Programming Learning Website! !

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