PHP: Convert Image to Base64 Encoding

By | December 11, 2015

Simple Image class, convert image to Base64 encoding.

class Image {
	public static function toBase64($image_location) {
		$image_path = $image_location;
		$image_type = pathinfo($image_path, PATHINFO_EXTENSION);
		$image_data = file_get_contents($image_path);
		$image_base64 = 'data:image/' . $image_type . ';base64,' . base64_encode($image_data);

		return $image_base64;
	}
}

Usage:

$b64 = Image::toBase64('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png');
Base64

Base64

2 thoughts on “PHP: Convert Image to Base64 Encoding

  1. Nanang

    mau tanya dong kalo file_get_contents error seperti ini kenapa ya? “file_get_contents(Lake_mapourika_NZ.jpeg): failed to open stream: No such file or directory” tapi kalo menggunakan gambar yang dari online “http://3.bp.blogspot.com/-hZhqHcfBKSg/TpxKA-8ffKI/AAAAAAAACY4/4pfiHDHr-58/s1600/a.jpg” jalan tapi kalo yang lokal “C:\fakepath\JPEG_example_JPG_RIP_100.jpg” kalo sperti itu ga ajalan mohon bantuannya bang terima kasih sebelumnya.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × two =