Stored image in Mysql BLOB, error when trying to display it

Hope someone help me with this mess. I am building a little mobile app that transforms a series of canvas objects to dataUrl then it encodes the data with btoa() method:

var canvas  = document.getElementById("imagen_envio");
var dataUrl = canvas.toDataURL('image/jpeg', .7);
var file = btoa(dataUrl);

After that it sends the file to a php file at the server using AJAX to store it in a Medium BLOB at MySQL. Everything it's working fine to this point but after that a php file must display the images but it's not working:

link: http://a.gob.mx/PHP_tratayretrata/img.php

//img.php
$connect = mysqli_connect($host, $user ,$password) or die("No se pudo conectar.");
mysqli_select_db($connect,$DB) or die("No se encuentra la base.");

$sql = "SELECT img FROM fotos WHERE usuario = 1 AND tema = 1 AND ejercicio = 1";
$result=mysqli_query($connect, $sql);

$row=mysqli_fetch_array($result);

header("Content-type: image/jpeg; charset=UTF-8");

$img = base64_decode($row["img"]);

echo '<img src="'.$img.'"/>';
?>

I made another php file that prints the data to text: http://a.gob.mx/PHP_tratayretrata/print-data.php and I used that data in a simple html file to be sure that the data is not corrupted: http://a.gob.mx/PHP_tratayretrata/test-data.html and it works!

So I have no idea what am I doing wrong. Any ideas? Thanks in advance!

Upvotes: 1

Views: 1849

Answers (2)

user2907541
user2907541

Reputation: 23

you need to remove hearder and if your are saving base64 encoded file to database then you don't need to decode it, your echo should be like this:

echo '<img src="data:img/jpeg;base64,'.$row['img']).'">';

Upvotes: 0

user1693593
user1693593

Reputation:

You are base-64 encoding a string that is already base-64 encoded as toDataURL() returns a data-uri which contains a data-uri header before the actual base-64 data.

This cannot be decoded into raw image-data.

You need to chop off the header from your data-uri, send that as-is to server (base-64 string). You can store that in the data base and decode it later.

/// this result is already a base-64 encoded string with a header
var dataUrl = canvas.toDataURL('image/jpeg', .7);

/// this will only base-64 encode again (incl. the header)
//var file = btoa(dataUrl);

A data-uri looks like this:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

So here you need to chop of the header up and including the last comma. The remaining data will be the base-64 encoded image.

Upvotes: 1

Related Questions