I have this database that contains images as strings. Those strings look something like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...
Try this:
echo '<img src="data:image/png;base64,' . $base64encodedString . '" />
If you are dealing with data stored in a PostgreSQL database bytea field you will receive a stream when fetching the PDO. To process the data any further first transform the stream to usual data like this: $stream = $row['content']; rewind($stream); $data=stream_get_contents($stream);
How to decode a base64 string (gif) into image in PHP / HTML
In the case you strip out the first case and choose to decode the string, you should add this before echoing the decoded image data:
header("Content-type: image/gif");
$data = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo base64_decode($data);
In the second case, use this instead:
echo '<img src="data:image/gif;base64,' . $data . '" />';
The second case is bad because the browser does not perform caching if the same image is shown on multiple pages.
Use this:
$code_base64 = $row['content'];
$code_base64 = str_replace('data:image/jpeg;base64,','',$code_base64);
$code_binary = base64_decode($code_base64);
$image= imagecreatefromstring($code_binary);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
try this
//your image data
$logodata = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo '<img src="data:image/gif;base64,' . $logodata . '" />';
/**
* @param $base64_image_content
* @param $path
* @return bool|string
*/
function base64_image_content($base64_image_content,$path){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
$new_file = $path."/".date('Ymd',time())."/";
$basePutUrl = C('UPLOAD_IMG_BASE64_URL').$new_file;
if(!file_exists($basePutUrl)){
//Check if there is a folder, if not, create it and grant the highest authority.
mkdir($basePutUrl, 0700);
}
$ping_url = genRandomString(8).time().".{$type}";
$ftp_image_upload_url = $new_file.$ping_url;
$local_file_url = $basePutUrl.$ping_url;
if (file_put_contents($local_file_url, base64_decode(str_replace($result[1], '', $base64_image_content)))){
ftp_upload(C('REMOTE_ROOT').$ftp_image_upload_url,$local_file_url);
return $ftp_image_upload_url;
}else{
return false;
}
}else{
return false;
}
}