php The method of converting base64 into an image: first get the value passed by the front end; then set the file path and named file name; then write the data flow file into the created file content; finally return the path information to Just use it on the front end.
Recommended: "PHP Video Tutorial"
Convert base64 data stream file to image file
When the front-end and back-end interact to process images, the following situation will occur:
What the front-end passes to our back-end is the base64 image data stream. All we need to do is convert it to The image is saved and then decided whether to return the image storage path information to the front end as needed.
Let’s talk about how to deal with this. In fact, it is very simple. It is a process of transcoding and storage.
1. Assume that the front-end is now streaming the data (here you can use online tools to transcode a local image into base64 format and then use it for testing)
2. We After receiving, a simple writing and storage operation is required.
3. The code is as follows
// $base_img是获取到前端传递的值 $base_img = str_replace('data:image/jpg;base64,', '', $base_img); // 设置文件路径和命名文件名称 $path = "./"; $prefix = "img_";//前缀可不写 $output_file = $prefix.time().rand(100,999).'.jpg'; $path = $path.$output_file; // 创建将数据流文件写入我们创建的文件内容中 file_put_contents($path, base64_decode($base_img)); // 输出文件 print_r($output_file);
4.ok, that’s it. You can return path information to the front end for use.
The above is the detailed content of How to convert php base64 to image. For more information, please follow other related articles on the PHP Chinese website!