简体   繁体   中英

Javascript assemble image from Base64?

Hello I have an image stored in a database it looks like this:

     iVBORw0KGgoAAAANSUhEUgAAAVEAAACsCAYAAADCDZ8x......

Its base64. I have the following PHP code:

<?php

include_once "mysql_connect.php";
if(isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM `entree` WHERE `realID` = '$id'");

while($row = mysql_fetch_assoc($query)){
    $imageData = $row[6];
    $imageType = $row[3];
    $imageData = base64_decode($imageData);
}

if($imageType == "image/png"){
    header("content-type: image/png");
}else if($imageType == "image/jpeg"){
    header("content-type: image/jpeg");
}else{}

if(!($imageData == null)){
echo $imageData;
}else{
    echo $imageData;

}


}else{

}



?>

Here is the HTML/PHP:

$SRC ="generateThumbnail64.php?id=$realid"; 

echo "<div id = \"feature0\" align=\"left\" >
<a href=\"".$url."\"><img src=\"$SRC\" alt = \"article thumbnail\" id=\"titleImg\"/></a>
<div id = \"feature2_1\">
  <a href= \"$url\" id = \"titletext\" alt = \"article title\">$donetitle</a>
  <div id = \"feature2_2\">
  <p id=\"resultuser\" >$username1 <b style=\"color:black;font-style:normal;\">&nbsp;&nbsp;&#x25cf;&nbsp;&nbsp;".$finviews." views</b></p>
  <p id=\"resultp2\">$donedesc1</p>
  </div>
  </div>
 </div>";

This is supposed to reassemble the bae64 into an image but it doesn't. Why doesn't this work? The result that is echoed is used as the SRC value in an image. If it matters the Base64 is stored in a database in a longtext type of value. How can I make it work?

Tell the broswer that you are using a data-uri. The way you use data-uri's is data:[<MIME-type>][;charset=<encoding>][;base64],<data>

there is no need of charset in your case, so the image src should be - data:image/<image_encoding>;base64,<base_64_encoded_data>

Note the semicolons and commas. Ignore angle brackets. They are just to make things a bit clearer not to be used in code.

By the way, this is not awesome code, but good enough. It is vulnerable to XSS.

if(isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM `entree` WHERE `realID` = '$id'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM