How to convert an image to binary image in PHP?

In this article, we will discuss how to convert a raw image to a binary image in PHP.

First of all, we will discuss what exactly a binary image is.

What is a binary image?

A binary image is a 64bit encoded binary data that takes 33% more data than the original image. It is basically applied to images with less size for faster loading of the image.

How to convert to a binary image in PHP

In PHP, the base64_encode() method converts the original image to a binary image. It needs the base URL of an image to perform the task.

You may also learn: How To Add text to image in PHP

Syntax:-

base64_encode($image);

The example is as follows,

<?php  
  
// image to string conversion
$imagelink = file_get_contents('https://www.codespeedy.com/wp-content/themes/CodeSpeedy-March-2019/img/CodeSpeedy-Logo.png'); 
  
// image string data into base64 
$encdata = base64_encode($imagelink);

  
// Output
echo $encdata; 
?>

Output:-




iVBORw0KGgoAAAANSUhEUgAAAMIAAACpCAMAAABODBKaAAAAOVBMVEX//////+Xd/////+JvOLBUwf+V4f+5gLCVXrD/wssVOMu5////4dhFOLAVXthvwv9FovLdor0VgOWHRjGwAAAABHRSTlMAAAAAs5NmmgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAAEgAAABIAEbJaz4AAANQSURBVHja7ZzJttwgDESdgRhnxPn/j80iq7YFxqIoeO6qdR/RFxAGJLQskiRJkiRJkiRJkiRJ76FPX8OLvuV/ulb/kqcYzqpHGM+xBVM3EUL4/mMQwM9fAYQQwu/PIwhy/8aFEMIfPkEMWISQJiJwIrDHofRXvAjcpWkLPRCYPn38loEQmFNpD30QiMMQOyHwhiH7TWtGSCyEi3n03gg0Z1i7IdCcIfZDSByCrDf/rbexzohwt3Hbyo1egCPc7z7zE09CsDZInnOXZYe0JG2g3rOGYSBCAiGQTtHWl821nsepEFynlXE3Mjuq84TQoBWFAJuRQnhvhG0mBN9HVQhCEMJ/WQePYQi+k4qFwDn/RyE8CcE681AQrIZTT0tf4AjW8PsQrPGkIFiruXP466akEAzBTv+1xzY8AvC4uFb1BhzB8mbv1UndgMIRrJ7zIpix39OIUhC8l7nmBfPJGBrBDAwkpzE7fn2cSmAEO8zm3iGb8aLjtMQi2AT+i9Aqe0iEXN5CclvMxbxe5hIOwZVChTCKQSgGKluCSzUpNQSEpuNuheX+CG0RvmI+BwmhNTq2D0dojyytoxEA9z5XxvsiYKJ7+0AEVJR4G4aQMABLdl36QKOQm0kfxxey/qwVqbKVB3wXmv2htNFj7ZFSk+Vi7rR2qvUNtWxVy4nHSIQyRsMw7BVGocf/TIJqgiO8DCzjBsOPUPWqjHGP5F9XzcnZ9x4pM5fcATIT4ehaaARQnm3BWPc7VbPjvAiDbrZRibY5W2fHwkd5Yk2zdbIWh3T61dSBqrrMNk7EExdro6QLA1NwgHOyGaFr3BkvYPJHXQLDzAi4hJRhfTcsmQeHMFVK1QMQcIltD8iQFAIb4QHZwkIQwkEPeEXygLc8vpafiUB64/kAhJ7PVIXQguDZIyOTdm8K9erc6oqBD+c9G72BCHZ87G7j89XBuNc+oqBJiy7KbBVd8qqoT+IgXJW1aUFgVebZ+yGw6s5t3RBo9TAvnKEBgeTNy5UzNCDwCudtnRCYdVVjH4TEIygPgxuBWxd27YFALjIc8QjsuraFhdWJMFNlXh/CkFLVGxBhTIXnxfNGDP2qDKGbR3jgS2OsoheBtyeSJEmSJEmSJEmSJEkaqH+bT4RNYLoIXAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxOC0wNy0xMFQwOTowNTo1MS0wNTowMGAO7pQAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTgtMDctMTBUMDk6MDU6NTEtMDU6MDARU1YoAAAAAElFTkSuQmCC

Note:-

  • In the above script, file_get_contents() method load an image from a path.
  •  file_get_contents() method can also load an image from a link.

Example of Image from a path is as follows,

$image_path=file_get_contents('D:/PICS/Pexels/photo-814194.jpeg');

 

In this way, we can convert an image to binary from raw image using PHP. If you have any doubts about this article, leave a comment below.

See also,


Leave a Reply

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