试图将图片通过json进行传输,这个时候就想到利用base64编码的方法来图片。主要步骤有
1、对图片文件进行编码,转换为base64编码的格式,及一长串字符;
2、可将字符通过json进行传送;
3、目的方接收json数组,取出编码字符串,并进行解码,显示图片
该方法难点主要还是在于对图片的编解码处理,以下是用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], '