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 = './uploads/14391214729290.jpg'; //读取图片文件,并转换成base64编码格式 $image_info = getimagesize($image_file); $base64_image_content = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($image_file))); //echo $base64_image_content; //将base64字符串解码并保存为原来图片格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = "./newfile.{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ echo '新文件保存成功:', $new_file; } } //显示图片 <img src="<?php echo $base64_image_content;?>" /> ?>
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>
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.