Home  >  Article  >  Backend Development  >  Detailed introduction to how PHP converts base64 data stream files into image files?

Detailed introduction to how PHP converts base64 data stream files into image files?

黄舟
黄舟Original
2018-05-11 11:54:215435browse

During development, I encountered an image displayed by a base64 data stream file used by the front end when uploading images.

That is to say

<img src="data:image/jpg;base64," />

***The jpg behind image/ is our image file format, and the long string after (base64,) is the specific file information.

data:image/jpg;base64 refers to the file header. We can put all the contents in src in the address bar of the browser and enter the

line to access it, and the image file can be displayed normally.

After I get the value of src to the background, I process it in the background. The method here will not be explained in detail.

//  $base_img是获取到前端传递的src里面的值,也就是我们的数据流文件
$base_img = str_replace(&#39;data:image/jpg;base64,&#39;, &#39;&#39;, $base_img);
//  设置文件路径和文件前缀名称
$path = "./";
$prefix=&#39;nx_&#39;;
$output_file = $prefix.time().rand(100,999).&#39;.jpg&#39;;
$path = $path.$output_file;
//  创建将数据流文件写入我们创建的文件内容中
$ifp = fopen( $path, "wb" );
fwrite( $ifp, base64_decode( $base_img) );
fclose( $ifp );
// 第二种方式
// file_put_contents($path, base64_decode($base_img));
// 输出文件 
print_r($output_file);

Online conversion tool link: tool.css-js.com/base64.html

The above is a detailed introduction to how PHP converts base64 data stream files into image files?, more For related content, please pay attention to the PHP Chinese website (www.php.cn)!

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