接到一個 case 需要把圖片轉為 base64 傳出,順手寫了個 class 做掉這件事。
<?php class ImageToBase64 { public function encode64($source = null, $fileName = null) { $source = file_get_contents($source); $type = pathinfo($fileName, PATHINFO_EXTENSION); $content = 'data:image/' . $type . ';base64,' . base64_encode($source); return $content; } public function decode64($source = null) { $content = null; if (preg_match('/data:([^;]*);base64,(.*)/', $source, $matches)) { header('Content-Type: '.$matches[1]); $content = base64_decode($matches[2]); } return $content; } }