Trying to transfer images through JSON, this is the time to think of using Base64 encoding method to image. The main steps are
1, the image file encoding, converted to Base64 encoded format, and a long string of characters;
2, the character can be transmitted through JSON;
3, the destination party receives the JSON array, takes out the encoded string, and decodes, displays the picture
The difficulty of this method is mainly in the processing of the image codec, the following is the implementation of PHP encoding and decoding processing code
<?php $image _file = './uploads/14391214729290.jpg '; Read the picture file and convert it into Base64 encoded format $image _info = getimagesize ($image _file); $base 64_image_content = "data:{$image _info[' mime ']};base64,". Chunk_split (Base64_encode (file_get_contents ($image _file)); echo $base 64_image_content; Decodes the Base64 string and saves it as the original picture format if (Preg_match ('/^ (data:\s*image\/(\w+); base64,)/', $base 64_image_content, $result)) { $type = $result [2]; $new _file = "./newfile. {$type} "; if (file_put_contents ($new _file, Base64_decode (Str_replace ($result [1], ", $base 64_image_content)))) { echo ' New file saved successfully: ', $new _file; } } Show picture "/>?>
which
Preg_match ()
function : performs a regular expression match
return value: pattern
The number of matches returned. Its value will be 0 times (mismatched) or 1 times, because Preg_match () will stop the search after the first match. If an error occurs , Preg_match () returns FALSE
.
file_put_contents ()
Function: writes a string to a file
Return value: The function successfully returns the number of bytes written to the data in the file, and returns when failed FALSE。
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Using Base64 to encode and decode images