Home >Backend Development >PHP Tutorial >Use base64 to encode and decode images

Use base64 to encode and decode images

WBOY
WBOYOriginal
2016-07-30 13:31:591665browse

Trying to transmit pictures through json, this time I thought of using base64 encoding method to encode pictures. The main steps are

1. Encode the image file and convert it into base64 encoded format and a long string of characters;

2. The characters can be transmitted through json; <br>

3. The destination receives the json array and takes it out Encode the string, decode it, and display the picture

The main difficulty of this method lies in the encoding and decoding of the picture. The following is the encoding and decoding code implemented in PHP

<?php
        $image_file = &#39;./uploads/14391214729290.jpg&#39;;

        //读取图片文件,并转换成base64编码格式
        $image_info = getimagesize($image_file);
        $base64_image_content = "data:{$image_info[&#39;mime&#39;]};base64," . chunk_split(base64_encode(file_get_contents($image_file)));
        //echo $base64_image_content;

        //将base64字符串解码并保存为原来图片格式
        if (preg_match(&#39;/^(data:\s*image\/(\w+);base64,)/&#39;, $base64_image_content, $result)){
            $type = $result[2];
            $new_file = "./newfile.{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], &#39;&#39;, $base64_image_content)))){
                echo &#39;新文件保存成功:&#39;, $new_file;
            }

        }
        //显示图片
        <img src="<?php echo $base64_image_content;?>" />
 ?>
<br>Among them,

preg_match() <br>

Function: Perform a regular expression match

Return value: Return The number of matches for pattern. Its value will be 0 times (no match) or 1 time because preg_match() will stop searching after the first match. If an error occurs preg_match() returns FALSE. <br>

file_put_contents () <br>

Function: Write a string to the file

Return value: This function will return the number of bytes of data written to the file successfully, and return FALSE on failure.

<br><br>

<br>

<br>

Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the use of base64 to encode and decode images, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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