php如何将图片转换为base64编码

时间:2017-07-28
本文章向大家介绍php如何将图片转换为base64编码,需要的朋友可以参考一下。

我认为它应该是:

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

也可以这种方式用base64编码格式表示图像...找到PHP函数file_get_content,然后使用函数base64_encode

并得到结果准备str作为data:" . file_mime_type . " base64_encoded string。在img src属性中使用它。看下面的代码可以帮到你。

// A few settings
$img_file = 'raju.jpg';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

// Echo out a sample image
echo '<img src="'.$src.'">';