Encode Decode image using PHP
Hello,
I am describing here the way to
1) Encode image to generate a string
2) Decode image from a given encoded string
1) Here you need to specifiy the path of your image in variable ‘$image_path’
<?php
$image_path = 'test_image.gif'; //this will be the physical path of your image
$img_binary = fread(fopen($image_path, "r"), filesize($image_path));
$img_str = base64_encode($img_binary); // will produce the encoded string
echo '<img src="data:image/gif;base64,'.$img_str.'" />'; //you can display the image on browser screen using image tag, if jpeg or jpg image than use 'image/jpg'
?>
2) Here I am using the string produced from the exuting the code seen above, it can be any encoded string which is generated from image
<?php
$decoded_str = base64_decode($img_str); //pass the encoded string here
$im = imagecreatefromstring($decoded_str);
//below code will display the image on browser
if ($im !== false) {
header('Content-Type: image/gif');
imagegif($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
?>
Hope this is helpful.
