Nasrul Hazim Bin Mohamad

PHP: Convert Image to Base64 Encoding

Dec
11

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

Leave a Reply

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

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

thirteen − twelve =