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.
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 = '<img src="data:image/jpg/png/gif;base64,' . $base64 .'" >'; echo $encode; } ?>
Convert base64 string to image:
//第一个参数图片保存路径以及图片名称 需注意图片后缀 linux请注意文件权限 //第二个参数为图片的base64字符串 ps:下方会贴出图片base64的格式 以及注意事项 file_put_contents('./test_base2.jpg', base64_decode($base64));
Detailed explanation of image base64 string:
//读取图片数据 $gambar = fread($fp,filesize($file)); //获取图片base64 $base64 = chunk_split(base64_encode($gambar)); //$gambar->读取的是图片的数据流 //$base64->将图片数据流转换为base64
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==
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==
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) .'#'. base64_encode('举个例子')); //将需要追加的数据也转换为base64格式,注意 【#】符号
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!