PHP对Base64的支持非常好,有内置的base64_encode与base64_decode负责图片的Base64编码与解码。
编码上,只要将图片流读取到,而后使用base64_encode进行进行编码即可得到。
我们先来看看编码,直接摘抄网上的代码,示例如下:
$img = './IMG_20180729_203230.jpg'; function base64EncodeImage ($image_file) { $base64_image = ''; $image_info = getimagesize($image_file); $image_data = fread(fopen($image_file, 'r'), filesize($image_file)); $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data)); return $base64_image; } $base64_img = base64EncodeImage($img); echo $base64_img;
得到如下结果(内容太长,我这里截取部分)
data:image/jpeg;base64,/9j/4XfSRXhpZgAATU0AKgAAAAgAEAEAAAMAAAABCZAAAAEBAAMAAAABDMAAAAECAAMAAAADAAAB EAEOAAIAAAAHAAAAzgEPAAIAAAAHAAAA1gEQAAIAAAAJAAAA3gESAAMAAAABAAAAAAEaAAUAAAAB AAAA6AEbAAUAAAABAAAA8AEoAAMAAAABAAIAAAExAAIAAAAYAAAA+AEyAAIAAAAUAAABFgITAAMA AAABAAEAAIdpAAQAAAABAAABKoglAAQAAAABAAAitqQLAAcAAAAEaXBwAAAAI5BmYnRtZG4AAEhV QVdFSQAAQUxQLUFMMDAAAAAAAEgAAAABAAAASAAAAAFBTFAtQUwwMCA4LjAuMC4xMzEoQzAwKQAA CAAIAAgyMDE4OjA3OjI5IDIwOjMyOjMxAAAqAQ0ABwAAAAAAAAAAgpoABQAAAAEAAANIgp0ABQAA AAEAACJIiCIAAwAAAAEAAgAAiCcAAwAAAAEGQAAAkAAABwAAAAQwMjEwkAMAAgAAABQAACJYkAQA AgAAABQAACJskQEABwAAAAQBAgMAkgEACgAAAAEAAANQkgIABQAAAAEAACJQkgMACgAAAAEAAAM4 kgQACgAAAAEAAANAkgcAAwAAAAEABQAAkggAAwAAAAEAAQAAkgkAAwAAAAEAGAAAkgoABQAAAAEA AAMoknwABwAAAGQAACHkknwABwAAHoYAAANYknwABwAAAAUAACHekpAAAgAAAAcAACKAkpEAAgAA AAcA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