I want to insert a image in blob format to db.
how to write a program in zend framework.
a simple form
just choose one image and insert into db.
In your Zend form create a file element:
$element = new Zend_Form_Element_File('fileElement');
Then you can insert the uploaded image to your DB in BLOB format like this:
$conn = new PDO("mysql:host='host';dbname='database'", 'userName', 'password');
$imagePath = $zendForm->fileElement->getFileName();
$image = file_get_contents('$imagePath');
$sql = "INSERT INTO images (data) values(?)";
$q = $conn->prepare($sql);
$q->bindParam(1, $image, PDO::PARAM_LOB);
$q->execute();
Read it in as a string using file_get_contents and store that.
That said, it is seldom a good idea to store the actual image data in the database. It is better practice to generate a unique filename and store that in the DB instead.
Here is some code to save the file in zend:
// This is to save in saveAction()
$source = $this->view->form->upload->getFileName();
$fp = fopen($source,'r');
$content = fread($fp,filesize($source));
// I don't use addslashes, because i already have that in my mapper
fclose($fp);
$model->image = base64_encode($content);
// Save here
// This is to read in imagesAction()
$this->_helper->Layout()->disableLayout();
$this->_helper->ViewRenderer->setNeverRender();
header('Content-Type: image/gif');
echo base64_decode($image);
exit;
I had alot of problems with it, try to make your save work and don't insert it into the database directly to test the reading. This won't make it possible unless you know the correct db encoding (which i don't).
Related
I'm using an odbc connection to connect to an SQL server. I need to display all the fields below:
Name: ID
Type: tinyint
Name: GroupId Type: smallint
Name: PhotoType: image
I'm using the code below which obviously isn't working:
<?php
$serverName = "TESTSERV\SQLEXPRESS"; //serverName\instanceName
$database = "test";
$user = "sa";
$password="#r#g0nSQLS#";
$DSN_TEST="TESTSERV - TEST";
$DSN_InetDb="TESTSERV - InetDb";
$DSN_taclog="TESTSERV-TACLOG";
$DSN_general="odbc-test";
$conn_TEST = odbc_connect ($DSN_TEST, $user, $password);
$conn_InetDb = odbc_connect($DSN_InetDb, $user, $password);
$conn_taclog = odbc_connect($DSN_taclog, $user, $password);
$conn_general=odbc_connect($DSN_general, $user, $password);
//confirming connectivity
if ($conn_general){
echo ('Connected'.'<br>');
}
else{
echo ('Not connected');
}
$sql = "SELECT * FROM InetDb.dbo.IndivImages WHERE IndivNdx = 30";
$sql_run = odbc_exec($conn_general,$sql);
$row = odbc_fetch_array($sql_run,3);
echo'<img src="data:image/jpeg;base64,'.base64_encode($row['UserImage']).'">';
?>
When executing this code, images are replaced with a chunk of characters.
How would I be able to return the images instead of a random characters ?
Thanks in advance,
J
You won't end up with actual images if you just echo out binary -- or base64-encoded -- data you've stored in the database. You'll just get the raw data blurted out.
If your images are stored as binary data, you need to serve it out via a script that outputs an image header -- e.g. header('Content-Type: image/jpeg'); -- followed by echoing out the raw data. You would then link to it e.g. as <img src="imager.php?img_id=124123123..." />. You could pass the data between your script and the "imager" e.g. over a $_SESSION variable.
If your images are stored as base64-encoded data (or if you convert the raw data on the fly), you can also use <img src="data:image/jpeg;base64,foBar1Nwht3v5R..." />. Be aware though that this isn't exactly bandwidth-friendly, and is better reserved for icons etc. rather than large image files.
Third option is to simply write the image data to the filesystem and then link to it with a standard img tag. That would make your images more easily cacheable, too. (There are ways around to ensure caching with the above options too, but writing them out, even into a /tmp directory if they are not reused, may be a simpler approach, and also save you some database performance.)
I have two files;
image.php
<?php
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
//Your code to call database for image id (from _GET['id']), for instance:
$image_id = $_GET['pid'];
$data = mysql_query("Select img where pid = $image_id");
while($data = mysql_fetch_assoc($result)){
$image=$data['img'];
header("content-type: image/png");
echo $image;
}
?>
and ay.html to view the image;
<img src="image.php?pid=IMAGE_ID" />
After many examples I tried, and every thread on this site and elsewhere, I'm still getting this error;
The image"http....../image.php?pid=IMAGE_ID" cannot be displayed because it contains errors.
Any help would be appreciated.
By the way the MySql variable is a LONGBLOB called img
I wonder why there isn't a simple IMG type for MySQL variable!
You should post how you stored the image to see exactly what it's wrong with your code but as the error says the image has some kind of error hence it was not stored correctly to database.
Generally the steps to go from an image to binary data and reverse are as below:
Image to binary conversion:
<? php
$image_data=file_get_contents('test.jpg');
$encoded_image=base64_encode($image_data);
echo $encoded_image;
?>
Binary to image conversion:
<?php
$image_data = file_get_contents('test.jpg');
$encoded_image = base64_encode($image_data);
$decoded_image = base64_decode($encoded_image);
echo $decoded_image;
?>
What you're missing altogether is the base_64 encode to prevent symbols from being incorrectly ttransformed.
/In your html page.../
/* */
I have successfully added the original image into my imgs/ folder and also onto the server. But I'm wanting to add the thumbnail into the database. I've added it into the imgs/ folder but can't seem to find away to insert it into the database.
This is the final bit of code that is used to crop the img and insert it to the folder.
I need to insert it into the database also so I can call on it for the $_SESSION User and the Users friend as I have profiles.
if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
if(isset($_GET['a'])){
if ($_GET['a']=="delete"){
if (file_exists($large_image_location)) {
unlink($large_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic_small='".$img."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$img')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
}
Hope someone can help. Thanks.
If you want to add in your database the path of thumbnail ($thumb_image_location), just add the code that inserts the path before unlink().
If you want to store the whole image into database, you need the column to be MEDIUMBLOB type, then, before unlink() read the code of the file that contains the image, for example with:
$img = file_get_contents($thumb_image_location);
Then, INSERT data stored in $img into your database.
Ideally, you don't want to be adding the thumbnail itself to the database, just a reference (filepath) to the file. So, while I don't know what your database looks like, you need to go through the following steps:
Create a field in your table called 'thumbnail' or similar. This will hold the name which the thumbnail file is saved as.
Add the filepath to the database immediately after you crop the large image (ie between the lines '$cropped = ...' and 'header("location....' in your code)
Whenever a user or user's friend is logged in, check this field and pull any thumbnail images referenced in the table.
And that is basically it.
If you want to store only the path of the Image into Database ,than it's fine to insert only the path and serve it with HTML.
Otherwise if you want to store the raw data of the image into Database than you have to encode the Image into base64 String .
Sending/Displaying a base64 encoded Image - Here is how you encode and image at base64.
And store this huge string into a Blob Field Type into databse.
You can use this:
// Read the file
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
$data = addslashes($data);
fclose($fp);
// Create the query and insert into our database.
// image is an BLOB field type
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
I have tried to download images to a directory but now I want to save the images to the database using BLOB type by not using the File Chooser. I mean save the images direct from a URL:
Say:
http://someserver.com/images/imageone.gif
How can I save that directly to database? Do I have to download it first before saving to database? Please help me..
Like you would save any other data.
$imageContents = file_get_contents('http://someserver.com/images/imageone.gif');
$imageContentsEscaped = mysql_real_escape_string($imageContents, $link);
mysql_query("INSERT INTO table_name (imageData) VALUES ('$imageContentsEscaped')", $link);
Make sure the column you want to save the image data to is set to a binary type such as BLOB.
// download image to memory
$image = file_get_contents('http://example.com/my/image.jpg');
// open PDO connection
$db = ...;
// insert downloaded data to the DB
$sql = 'insert into my_table(filename, content) values (?,?)';
$stmt = $db->prepare($sql);
$stmt->bindParam(1, 'my/image.jpg');
$stmt->bindParam(2, $image, PDO::PARAM_LOB);
$stmt->execute();
Using the above technologies, I want to create a PDF, store it in my db, and email it. All with the click of one button.
I also want to call it up and have it be able to display with a hyperlink.
I am very new to FPDF. Therefore, I am trying to start off very slowly.
I began with this link stackoverflow Q
I put both parts of his code into the same page and tried with separate pages. I made the suggested changes/additions and even did a line by line comparison.
I still get the message, "format error: not a PDF or corrupted"
If I just $pdf->Output(); I get the pdf to display. It's either the way the string is being Output, or it's the header() function. It's not the storage method, unless my column setup is incorrect. BUt a blob is a blob, right?
If you want, I can upload the sanitized code. Just let me know what would help answer this.
Thanks
JJ
here's the code on request
here's where I enter it in:
<?php
session_start();
include "server.php";//my file to connect to db
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$content = $pdf->Output("", "S"); //return the pdf file content as string
$sql = "update table set table_pdf= '".addslashes($content)."' " .
"where table_id = '188'";
mysql_query($sql);
//here's where I retrieve it
$sql2 = "select table_pdf from table where table_id = '188'";
$result2 = mysql_query($sql2);
$rs = mysql_fetch_assoc($result2);
$content2 = $rs['rdngs_hdr_pdf'];
header('Content-Type: application/pdf');
header("Content-Length: ".strlen(content2));
header('Content-Disposition: attachment; filename=myfile.pdf');
print $content2;
?>
Like I said, I have tried the other ideas on the other question link above. right now it just sits on the version where the addslashes is there.
Thanks for any help.
Give this a try. Instead of using the addslashes to escape the content, try using unpack to get it in a binary represenation:
$content = $pdf->Output("", "S"); //return the pdf file content as string
$data = unpack("H*hex", $content);
$sql = "update table set table_pdf= " . 0x".$data['hex']." . " " .
"where table_id = '188'";
For retrieving the data you should be able to just do a select, and then output the content, just like you are already doing.