Convert image to blob php

<?php
$file_name = $_FILES['files']['name'];
$tmp_name  = $_FILES['files']['tmp_name'];
$file_size = $_FILES['files']['size'];
$file_type = $_FILES['files']['type'];

// The codes written above work fine and have proper information.

$fp = fopen($tmp_name, 'r'); // This one crashes.
$file_content = fread($fp, $file_size) or die("Error: cannot read file");
$file_content = mysql_real_escape_string($file_content) or die("Error: cannot read file");
fclose($fp);

....

I'm a newbie to PHP stuff. I'm trying to store a jpg image as blob in a database but terribly struggling with it :( I tried many tutorials and read documents but still no luck. Any suggestions or tutorials that might help me out..?

asked Oct 21, 2011 at 5:13

2

When opening binary files with fopen(), use the rb mode, ie

$fp = fopen($tmp_name, 'rb');

Alternatively, you may simply use file_get_contents(), eg

$file_content = file_get_contents($tmp_name);

To enable better error reporting, place this at the top of your script

ini_set('display_errors', 'On');
error_reporting(E_ALL);

answered Oct 21, 2011 at 5:43

PhilPhil

147k21 gold badges229 silver badges230 bronze badges

1

For the mimetype, see Mimey or another lib like it.
Or this shortcut might work for some file types like png and jpg: $mimetype = "image/".pathinfo($path,PATHINFO_EXTENSION);

$path = //path/to/file.jpg (or whatever)

$mimer = new \Mimey\MimeTypes();
$mimetype = $mimer->getMimeType(pathinfo($path,PATHINFO_EXTENSION));

$source = file_get_contents($path);
$base64 = base64_encode($source);
$blob = 'data:'.$mimetype.';base64,'.$base64;

$html = '<img src="'.$blob.'" alt="Description for differently abled humans." />';
echo $html;

Common Mime Types

Mdn has a list of common mime types.

For your convenience here are the (probably) most common image ones:

  • .gif: image/gif
  • .jpg or .jpeg: image/jpeg
  • .png: image/png

    Table of contents
  • How to convert jpg image to proper blob data type using php
  • Php : Convert a blob into an image file
  • MySQL BLOB using PHP
  • How to convert the JPEG image to blob?
  • How to Display Blob Image in PHP from Database

How to convert jpg image to proper blob data type using php

<?php
$file_name = $_FILES['files']['name'];
$tmp_name  = $_FILES['files']['tmp_name'];
$file_size = $_FILES['files']['size'];
$file_type = $_FILES['files']['type'];

// The codes written above work fine and have proper information.

$fp = fopen($tmp_name, 'r'); // This one crashes.
$file_content = fread($fp, $file_size) or die("Error: cannot read file");
$file_content = mysql_real_escape_string($file_content) or die("Error: cannot read file");
fclose($fp);

....
$fp = fopen($tmp_name, 'rb');
$file_content = file_get_contents($tmp_name);
ini_set('display_errors', 'On');
error_reporting(E_ALL);

Php : Convert a blob into an image file

$image = imagecreatefromstring($blob); 

ob_start(); //You could also just output the $image via header() and bypass this buffer capture.
imagejpeg($image, null, 80);
$data = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/jpg;base64,' .  base64_encode($data)  . '" />';
$image = new Imagick();
$image->readimageblob($blob);
echo '<img src="data:image/png;base64,' .  base64_encode($image->getimageblob())  . '" />';
$image = new Gmagick();
$image->readimageblob($blob);
echo '<img src="data:image/png;base64,' .  base64_encode($image->getimageblob())  . '" />';
$path = "/tmp/images";
$sql = "SELECT image_name, image_content FROM images";

$result = mysql_query($sql, $db_con);
if (!$result) {
   $message  = 'Invalid query: ' . mysql_error() . "\n";
   $message .= 'Whole query: ' . $sql;
   die($message);
}

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
   $image = $row["image_contents"];
   $name = $row["image_name"];

   // option 1
   $file = fopen($path."/".$name,"w");
   echo "File name: ".$path."$name\n";
   fwrite($file, base64_decode($image));
   fclose($file);

   // option 2 (oneliner)
   // file_put_contents($path."/".$name, base64_decode($image));
}
<?php
if(isset($_REQUEST['id']))
{
   // get the file with the id from database
      include "dbconfig.php";
      $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
      mysql_select_db($dbname, $dbconn) or die("Unable to select database");

      $id    = $_ REQUEST ['id'];
      $query = "SELECT `img_name`, `img_type`, `img_size`, `img_data`
                       FROM img_tbl WHERE id = ‘$id’";

      $result = mysql_query($query) or die(mysql_error());
      list($name, $type, $size, $content) = mysql_fetch_array($result);

      header("Content-length: $size");
      header("Content-type: $type");
      print $content;

      mysql_close($dbconn);
}
?>

MySQL BLOB using PHP

CREATE TABLE IF NOT EXISTS `output_images` (
  `imageId` tinyint(3) NOT NULL AUTO_INCREMENT,
  `imageType` varchar(25) NOT NULL DEFAULT '',
  `imageData` mediumblob NOT NULL,
  PRIMARY KEY (`imageId`)
)
<?php
if (count($_FILES) > 0) {
    if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
        require_once "db.php";
        $imgData = addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
        $imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
        
        $sql = "INSERT INTO output_images(imageType ,imageData)
	VALUES('{$imageProperties['mime']}', '{$imgData}')";
        $current_id = mysqli_query($conn, $sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error($conn));
        if (isset($current_id)) {
            header("Location: listImages.php");
        }
    }
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
    <form name="frmImage" enctype="multipart/form-data" action=""
        method="post" class="frmImageUpload">
        <label>Upload Image File:</label><br /> <input name="userImage"
            type="file" class="inputFile" /> <input type="submit"
            value="Submit" class="btnSubmit" />
    </form>
    </div>
</BODY>
</HTML>
<?php
    require_once "db.php";
    if(isset($_GET['image_id'])) {
        $sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
		$result = mysqli_query($conn, $sql) or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysqli_error($conn));
		$row = mysqli_fetch_array($result);
		header("Content-type: " . $row["imageType"]);
        echo $row["imageData"];
	}
	mysqli_close($conn);
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" />
<?php
    require_once "db.php";
    $sql = "SELECT imageId FROM output_images ORDER BY imageId DESC"; 
    $result = mysqli_query($conn, $sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
	while($row = mysqli_fetch_array($result)) {
	?>
		<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
	
<?php		
	}
    mysqli_close($conn);
?>
</BODY>
</HTML>

How to convert the JPEG image to blob?

FileStram imgStream = File.OpenRead("C:\\photos\me.jpg");
byte[] blob = new byte[imgStream.Length];
imgStream.Read( blob, 0, (int)imgStream.Length);

imgStream.Dispose( );

How to Display Blob Image in PHP from Database

<html>
<head>
<title>Display Blob Image in PHP</title>
</head>
<body>
    <form enctype="multipart/form-data" action="upload.php" method="post">
        <label>Upload the image file:</label><br /> 
        <input name="userImage" type="file" /> 
        <input type="submit" value="Upload" />
    </form>
    </div>
</body>
</html>
<?php
if(isset($_POST["submit"])){

    $b = getimagesize($_FILES["userImage"]["tmp_name"]);

    //Check if the user has selected an image
    if($b !== false){
        //Get the contents of the image
        $file = $_FILES['userImage']['tmp_name'];
        $image = addslashes(file_get_contents($file));
        
        $host     = 'localhost';
        $username = 'root';
        $password = ' ';
        $db     = 'test';
        
        //Create the connection and select the database
        $db = new mysqli($host, $username, $password, $db);
        
        // Check the connection
        if($db->connect_error){
            die("Connexion error: " . $db->connect_error);
        }
        
        //Insert the image into the database
        $query = $db->query("INSERT into gallery (image) VALUES ('$image')");
        if($query){
            echo "File uploaded successfully.";
        }else{
            echo "File upload failed.";
        } 
    }else{
        echo "Please select an image to upload.";
    }
}
?>
<?php
if(!empty($_GET['id'])){

    $host     = 'localhost';
    $username = 'root';
    $password = ' ';
    $db     = 'test';
    
    //Create the connection and select the database
    $db = new mysqli($host, $username, $password, $db);
    
    // Check the connection
    if($db->connect_error){
        die("Connexion error: " . $db->connect_error);
    }
    
    //Get the image from the database
    $res = $db->query("SELECT image FROM gallery WHERE id = {$_GET['id']}");
    
    if($res->num_rows > 0){
        $img = $res->fetch_assoc();
        
        //Render the image
        header("Content-type: image/jpg"); 
        echo $img['image']; 
    }else{
        echo 'Image not found...';
    }
}
?>

Convert BLOB image then save to file.

<img src="data:image/jpeg;base64,<?php echo base64_encode($content); ?>" width="100" />
	public function testImageConvert()
{
	$query = $this->db->query("SELECT Picture FROM `ItemPicture` LIMIT 1");

	if($query->num_rows() > 0)
	{
		$row = $query->row();

		file_put_contents('test.jpg',$row->Picture);
	}
	return false;
}

Next Lesson PHP Tutorial