I have an image field that is of type BLOB in my MySQL database, I collect the data through PDO, but when viewing it it does not show me anything, I have searched the internet and everywhere I got the same thing with src="data:image/jpeg;base64
.
This is my code:
<?php
require_once './BaseDatos.php';
$id = $_GET['id'];
$bd = new BaseDatos('foro');
$imagen = $bd->SenetenciaSelect("usuarios", ["id"=>$id])[0]["image"];
echo '<img src="data:image/jpeg;base64,'.base64_encode($imagen) .' "/>';
The variable $imagen
returns this if I display it:
ÿØÿà\0JFIF\0\0\0\0\0\0ÿþ\0;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90 ÿÛ\0C\0 %# , #&\')* )-0-(0%()(ÿÛ\0C (((((((((((((((((((((((((((((((((( (((((((((((((ÿÀ\0@ \0\"\0ÿÄ\0\0\0\0\0\0\0\0\0\0\0\0 ÿÄ\0µ\ 0\0\0}\0!1AQa\"q2'¡#B±ÁRÑð$3br‚ %&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š'“”•–—˜™š¢£ ¤¥¦§¨©ª²³´µ¶ ¸¹ºÂÃÄÅÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ\0\0\0\0\0\0\0\0 ÿÄ\0µ\0\0w\0!1AQaq\"2B'¡± á etc.
Everything points to it being a charset conversion issue corrupting your data
BLOB
or you're experiencing some issue related to using deprecated functions as of PHP 5.5mysql_*
or poor SQL escaping.Character set related issues:
If at any time you use
SET CHARACTER SET utf8
after establishing the connection, the client will start to perform character conversion even in the type fieldsBLOB
from the character set in which the table is.If you use instead
SET NAMES utf8
, both server and client will agree on the same charset for everything and there will be no client-side conversion to corrupt data.Look at the data on this page .
In it you can see that it
SET NAMES 'charset_name'
is equivalent to:However it
SET CHARACTER SET 'charset_name'
is equivalent to:Therefore, if the table is in its default value (
latin1_swedish_ci
) the data will be corrupted.Problems related to bad SQL escaping:
To properly insert the data into the database you should modify your code and use
mysql_real_escape_string()
instead ofaddslashes()
:That way you won't have problems with strange characters. You should also try using
mysql_set_charset()
.Still, I'd urge you to migrate your code to mysqli or, better yet, PDO . That way you can do prepared queries with field mapping where you won't have problems with string escaping.
I got this
EDIT: Complete example
Three possible solutions (@deprecated):
A. Using your variable
$imagen
after$imagen=$bd...
you put this and comment out the actual code you are trying to display the image in:B. Also using your variable
$imagen
after$imagen=$bd...
commenting your current code to display the image and copy and paste this:C. Doesn't work? Make sure your image is correct in the database.
Leading me by your comment on @a-cedano's answer. I put together a test and it seems that the problem is that before saving the BLOB you apply addslashes to it but you don't apply the stripslashes when retrieving the info
this is my test code, (assumes a valid test.jpg file in the same path)