How to convert an image to code in PHP

It is very important to protect your images from hackers and convert their base formats like JPG, PNG, and Bitmap into PHP code. For security, it’s very important and it saves your website loading time if all the images are coded.

image to code

In this blog post, we will explain the simple way of converting images to php code.

In PHP, you can convert an image to Base64 encoding, which is a common way to represent binary data as a text string. Here’s a simple example of how to convert an image to Base64 code using PHP:


function image_to_code($image_path, $output_format = ‘base64’)
// Check if the image file exists.
if (!file_exists($image_path)) {
return false;

// Get the image type.
$image_type = exif_imagetype($image_path);

// Validate the image type.
if (!in_array($image_type, [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG])) {
return false;

// Create an image resource object.
$image = imagecreatefromstring(file_get_contents($image_path));

// Convert the image to the output format.
switch ($output_format) {
case ‘base64’:
$output = base64_encode(imagepng($image));
case ‘data_uri’:
$output = ‘data:image/’ . image_type_to_extension($image_type, false) . ‘;base64,’ . $output;
$output = false;

// Destroy the image resource object.

return $output;

// Example usage:

$image_path = ‘/path/to/image.jpg’;

// Convert the image to base64.
$base64_encoded_image = image_to_code($image_path);

// Convert the image to a data URI.
$data_uri = image_to_code($image_path, ‘data_uri’);

// The base64 encoded image and data URI can now be used in code, for example to embed
// them in an HTML document or to send them over a network.


This code will output the Base64 representation of the image. You can use this Base64 string in HTML, CSS, or other contexts where you need to represent the image as text.

You can simply rename and use it as call back function for all images in your website.


Related articles

Printing Press Power: Balaji Predicts Debt Crisis Unveils Truth

Balaji S. Srinivasan, a prominent American entrepreneur and investor,...

Telegram’s Game Craze Pushes User Numbers Sky High

The number of Telegram users worldwide is surging as...

Hive’s Big Bitcoin Bet on Paraguay

Paraguay is making strides in its ambition to become...

Ether ETFs Light Up US Markets

Spot Ether exchange-traded funds have finally been given the...


Please enter your comment!
Please enter your name here