SitePoint Sponsor |
|
User Tag List
Results 1 to 13 of 13
-
Jun 17, 2007, 15:54 #1
- Join Date
- Jun 2007
- Posts
- 15
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
inserting image and thumbnail into DB
I am building a simple cms system for a site that is archiving books.I wish to allow the owner to upload an image title description etc into a DB. I have a simple script working which was taken from sitepoint -DB driven website chapter 10- filestore.php. However i need to either create a thumbnail on the fly or create one before hand and upload it with the main image. I don't know how to integrate this into the script i have already. Any help appreciated!
-
Jun 17, 2007, 19:17 #2
- Join Date
- Mar 2006
- Location
- Gold Coast, Australia
- Posts
- 1,369
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
You can use the GD library which is usually available on your server to resize an image. I wouldn't recommend adding images into the database, instead store a reference to the file location.
plenty of tutorials available, see gdStudiotime - Time Management for Web Developers
to-do's, messages, invoicing, reporting - 30 day free trial!
Thomas Multimedia Web Development
-
Jun 17, 2007, 19:51 #3
- Join Date
- Mar 2005
- Location
- Ukraine
- Posts
- 1,403
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
You may experiece image quality issues when using GD, consider ImageMagick.
-
Jun 18, 2007, 08:43 #4
- Join Date
- Jun 2007
- Posts
- 15
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
thanx guys but still confused
Had a look at GD library but got bogged down and spent hours achieving nothing.
Here is the code i am using. This will insert an image description etc in to 'filestore'. I am pulling everything back out but want to either generate thumbs to display in the DB or generate thumbs on the fly for display.
I looked at hundreds of tutorials which all deal with images that are in an 'image' folder , however mine are stored as 'medium blobs' in a DB
<?php
$dbcnx = @mysql_connect('localhost', 'root', 'password');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}
if (!@mysql_select_db('diseart')) {
exit('<p>Unable to locate the diseart ' .
'database at this time.</p>');
}
if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = '';
}
if (($action == 'view' or $action == 'dnld') and isset($_GET['id'])) {
$id = $_GET['id'];
// User is retrieving a file
$sql = "SELECT filename, mimetype, filedata
FROM filestore WHERE id = '$id'";
$result = @mysql_query($sql);
if (!$result) {
exit('Database error: ' . mysql_error());
}
$file = mysql_fetch_array($result);
if (!$file) {
exit('File with given ID not found in database!');
}
$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($action == 'dnld') {
$disposition = 'attachment';
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5') or
strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 7')) {
$mimetype = 'application/x-download';
}
}
header("content-disposition: $disposition; filename=$filename");
header("content-type: $mimetype");
header('content-length: ' . strlen($filedata));
echo($filedata);
exit();
} elseif ($action == 'del' and isset($_GET['id'])) {
$id = $_GET['id'];
// User is deleting a file
$sql = "DELETE FROM filestore WHERE id = '$id'";
$ok = @mysql_query($sql);
if (!$ok) {
exit('Database error: ' . mysql_error());
}
header('location: ' . $_SERVER['PHP_SELF']);
exit();
} elseif (isset($_FILES['upload'])) {
// Bail out if the file isn’t really an upload.
if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
exit('There was no file uploaded!');
}
$uploadfile = $_FILES['upload']['tmp_name'];
$uploadname = $_FILES['upload']['name'];
$uploadtype = $_FILES['upload']['type'];
$uploaddesc = $_POST['desc'];
// Open file for binary reading ('rb')
$tempfile = fopen($uploadfile, 'rb');
// Read the entire file into memory using PHP's
// filesize function to get the file size.
$filedata = fread($tempfile, filesize($uploadfile));
// Prepare for database insert by adding backslashes
// before special characters.
$filedata = addslashes($filedata);
$thumbdata = create_thumb($filedata);
// Create the SQL query.
$sql = "INSERT INTO filestore SET
filename = '$uploadname',
mimetype = '$uploadtype',
description = '$uploaddesc',
filedata = '$filedata',
thumbdata = '$thumbdata'";
// Perform the insert.
$ok = @mysql_query($sql);
if (!$ok) {
exit('Database error storing file: ' . mysql_error());
}
header('location: ' . $_SERVER['PHP_SELF']);
exit();
}
// Default page view: lists stored files
$sql = 'SELECT id, filename, mimetype, description FROM filestore';
$filelist = @mysql_query($sql);
if (!$filelist) {
exit('Database error: ' . mysql_error());
}
?>
<?
function create_thumb($filename){
//Resize the following jpg image
//$filename='/pathtoyourimage.jpg';
$array = getimagesize($filename);
$width_orig= $array[0];
$height_orig= $array[1];
//We resize to a max size of 640 either on the width size or height size
if($width_orig > $height_orig)
$ratio= $width_orig/640;
else $ratio=$height_orig/640;
$width=$width_orig/$ratio;
$height=$height_orig/$ratio;
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
//Output into another file - 50 is a pecentage of the original quality
imagejpeg($image_p,'resized-'.$filename, 50);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP/MySQL File Repository</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>PHP/MySQL File Repository</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="post" enctype="multipart/form-data">
<p><label>Upload Filebr />
<input type="file" name="upload" /></label></p>
<p><label>File Descriptionbr />
<input type="text" name="desc" maxlength="255" /></label></p>
<p><input type="submit" value="Upload" /></p>
</form>
<p>The following files are stored in the database/p>
<table>
<tr>
<th>Filename</th>
<th>Type</th>
<th>Description</th>
</tr>
<?php
if (mysql_num_rows($filelist) > 0) {
while ($f = mysql_fetch_array($filelist)) {
?>
<tr valign="top">
<td>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=view&id=<?php echo $f['id']; ?>">
<?php echo $f['filename']; ?></a>
<!-- would like to output an image here preferably generated-->
</td>
<td><?php echo $f['mimetype']; ?></td>
<td><?php echo $f['description']; ?></td>
<td>
[<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=dnld&id=<?php echo $f['id']; ?>"
>Download</a> |
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?action=del&id=<?php echo $f['id']; ?>"
onclick="return confirm('Delete this file?');"
>Delete</a>]
</td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="3">No Files!</td></tr>
<?php
}
?>
</table>
</body>
</html>
-
Jun 18, 2007, 22:37 #5
- Join Date
- Mar 2006
- Location
- Gold Coast, Australia
- Posts
- 1,369
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
i'm curious earl-grey, under what conditions have u seen quality issues with GD? filetypes, sizes etc. I haven't had any gripes with it yet, but I also haven't used it for diverse tasks.
katu, I don't know where you sourced that code from, but it is way too long. If you just want to deal with jpegs, it is easy. Also, please post code code in [ php ] [ /php ] tags without the spaces so its easy to read.
If you have a working upload form, then get the path of the uploaded file and run it through a resize function. heres one I prepared earlier.
PHP Code:function resizeImage($originalPath, $newPath, $newWidth, $quality)
{
$srcImg = @imagecreatefromjpeg($originalPath);
$origWidth = @imagesx($srcImg);
$origHeight = @imagesy($srcImg);
if ($origWidth > $newWidth) // must resize
{
$ratio = $newWidth / $origWidth;
$newHeight = $origHeight * $ratio;
$newImg = @imagecreatetruecolor($newWidth, $newHeight);
@imagecopyresampled($newImg,$srcImg,0,0,0,0,$newWidth,$newHeight,@imagesx($srcImg),@imagesy($srcImg));
if (!@imagejpeg($newImg, $newPath, $quality)) return false;
} else { // image is smaller than max width
$newImg = @imagecreatetruecolor($origWidth, $origHeight);
@imagecopyresampled($newImg,$srcImg,0,0,0,0,$origWidth,$origHeight,@imagesx($srcImg),@imagesy($srcImg));
if (!@imagejpeg($newImg, $newPath, $quality)) return false;
}
}
Studiotime - Time Management for Web Developers
to-do's, messages, invoicing, reporting - 30 day free trial!
Thomas Multimedia Web Development
-
Jun 18, 2007, 23:49 #6
- Join Date
- Mar 2005
- Location
- Ukraine
- Posts
- 1,403
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Original image
Medium-sized thumbnail, GD vs Medium-sized thumbnail, ImageMagick
Small thumbnail, GD vs Small thumbnail, ImageMagick
Here's the GD code:
PHP Code:// Generate the thumbnail
$img = imagecreatefromjpeg($dir . $file);
list($width, $height) = getimagesize($dir . $file);
$img2 = imagecreatetruecolor($twidth, $theight);
imagecopyresized($img2, $img, 0, 0, 0, 0, $twidth, $theight, $width, $height);
// Create file with the same name in the ./thumbs/ subdirectory
imagejpeg($img2, $dir . $subdir . $file);
imagedestroy($img);
PHP Code:$cmd = '/usr/bin/convert ';
$cmd .= '-resize 100x75! ';
$cmd .= $src . ' ' . $dst;
passthru($cmd);
-
Jun 19, 2007, 00:14 #7
- Join Date
- Jun 2007
- Posts
- 15
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks
I will rewrite code and try to figure out how to save to folders and data to DB. If i get all of this working I will tackle creating thumbnails. The reason i was opting for saving images in the Database rather than folders was because it would be easier to delete images and the records that go with each image all in one go
-
Jun 19, 2007, 00:24 #8
- Join Date
- Jun 2007
- Location
- Frankfurt/Germany
- Posts
- 66
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Very impressing...gd vs. IM.
-
Jun 19, 2007, 01:14 #9
- Join Date
- Oct 2006
- Location
- Kathmandu, Nepal
- Posts
- 4,013
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
I agree that the image quality issue is there between GD and ImageMagic and now i am more clear seeing early-grey's example. There may not be ImageMagick installed in the server, in that case GD is the best and easy to install. I have also a small class of GD for thumbnail and resize the images. Please have a look on my class and example.
PHP Code:class ImageUpload{
var $ArrImageType;
var $picpath;
var $thumbpath;
var $maxwidth;
var $thumbwidth;
var $thumbheight;
function __construct($picpath, $maxwidth, $thumbwidth = 100, $thumbheight = 100, $thumbpath = ""){
$this->maxwidth = $maxwidth;
$this->thumbwidth = $thumbwidth;
$this->thumbheight = $thumbheight;
$this->picpath = $picpath;
$this->thumbpath = $thumbpath;
$this->ArrImageType = array('image/gif', 'image/jpeg', 'image/jpg', 'image/pjpeg', 'image/png');
}
function Create_ThumbNail($ImageType, $rW, $rH, $imagename, $do="thumbnail"){
$full_picmain = $this->picpath . "/" . $imagename;
if($do != "thumbnail")
$tsrc = $this->picpath . "/$imagename";
else
$tsrc = $this->thumbpath . "/$imagename";
# Starting of GIF thumb nail creation #
if($ImageType == "image/gif"){
$im = imagecreatefromgif($full_picmain);
$width = imagesx($im); # Original picture width is stored
$height = imagesy($im); # Original picture height is stored
if($width > $rW){$n_width = $rW;}
else{$n_width = $width;}
if($height > $rH){$n_height = $rH;}
else{$n_height = $height;}
$newimage = imagecreatetruecolor($n_width,$n_height);
imagecopyresized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width,$height);
if(function_exists("imagegif")) {
header("Content-type: image/gif");
imagegif($newimage, $tsrc);
}
elseif(function_exists("imagejpeg")) {
header("Content-type: image/jpeg");
imagejpeg($newimage, $tsrc);
}
chmod("$tsrc", 0777);
}
# starting of JPG thumb nail creation #
if($ImageType == "image/pjpeg" || $ImageType == "image/jpeg" || $ImageType == "image/jpg"){
$im = imagecreatefromjpeg($full_picmain);
$width = imagesx($im); # Original picture width is stored
$height = imagesy($im); # Original picture height is stored
if($width > $rW){$n_width = $rW;}
else{$n_width = $width;}
if($height > $rH){$n_height = $rH;}
else{$n_height = $height;}
$newimage = imagecreatetruecolor($n_width,$n_height);
imagecopyresized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
imagejpeg($newimage, $tsrc);
chmod("$tsrc", 0777);
}
# starting of JPG thumb nail creation #
if($ImageType == "image/png"){
$im = imagecreatefrompng($full_picmain);
$width = imagesx($im); # Original picture width is stored
$height = imagesy($im); # Original picture height is stored
if($width > $rW){$n_width = $rW;}
else{$n_width = $width;}
if($height > $rH){$n_height = $rH;}
else{$n_height = $height;}
$newimage = imagecreatetruecolor($n_width,$n_height);
imagecopyresized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
imagepng($newimage, $tsrc);
chmod("$tsrc", 0777);
}
}
function Upload($PicFile){
if(is_uploaded_file($PicFile['tmp_name'])){
if($PicFile['size'] < 1048576 && in_array($PicFile['type'], $this->ArrImageType)){
$imgExt = $this->GetImageExtention($PicFile['type']);
$PicName = substr(md5(time()), rand(0, 26), 6) . "." . $imgExt;
$PicFullPathName = $this->picpath . "/" . $PicName;
if(move_uploaded_file($PicFile['tmp_name'], $PicFullPathName)){
$this->Create_ThumbNail($PicFile['type'], 100, 80, $PicName, "thumbnail"); # Create thumbnail image
list($width, $height) = getimagesize($PicFullPathName);
if($width > $this->maxwidth){ # default size.
$ratio = (($width - $this->maxwidth) * 100) / $width;
$newheight = $height - ($ratio * $height / 100);
$this->Create_ThumbNail($PicFile['type'], $this->maxwidth, $newheight, $PicName, "resize"); # resizing the image
}
mysql_query("UPDATE tblproductimages SET ProductImagePath='$PicName' WHERE PictureID='$newpicid'") or die(mysql_error());
}
}
}# is picture uploaded
}
# Get image extention #
function GetImageExtention($type){
if($type == "image/jpeg" || $type == "image/jpg" || $type == "image/pjpeg")
return "jpg";
elseif($type = "image/png")
return "png";
elseif($type == "image/gif")
return "gif";
}
}
$picpath = './uploads';
$thumbpath = './uploads/thumbnails';
$maxwidth = 600;
$thumbwidth = 100;
$thumbheight = 100;
$obj = new ImageUpload($picpath, $maxwidth, $thumbwidth, $thumbheight, $thumbpath);
$PicFile = $_FILES['PrdImg'];
$obj->Upload($PicFile);
Mistakes are proof that you are trying.....
------------------------------------------------------------------------
PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5
-
Jun 19, 2007, 03:24 #10
- Join Date
- Jun 2007
- Posts
- 15
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks Rajug
A beginner i certainly am! How do i call this class from the form where i am uploading my image.
I can see $PicFile is getting its data from $_FILES['PrdImg'];
but i don't know what is stored in that element of the $_Files array
-
Jun 19, 2007, 03:36 #11
- Join Date
- Oct 2006
- Location
- Kathmandu, Nepal
- Posts
- 4,013
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
There is nothing to call this class, i have called it like this at the end of my code above:
PHP Code:$picpath = './uploads';
$thumbpath = './uploads/thumbnails';
$maxwidth = 600;
$thumbwidth = 100;
$thumbheight = 100;
$obj = new ImageUpload($picpath, $maxwidth, $thumbwidth, $thumbheight, $thumbpath);
$PicFile = $_FILES['PrdImg'];
$obj->Upload($PicFile);
PHP Code:mysql_query("UPDATE tblproductimages SET ProductImagePath='$PicName' WHERE PictureID='$newpicid'") or die(mysql_error());
PHP Code:mysql_query("INSERT INTO tblproductimages SET ProductImagePath='$PicName') or die(mysql_error());
And finally, do you want to know how the functions are working or just use it for your purpose?Mistakes are proof that you are trying.....
------------------------------------------------------------------------
PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5
-
Jun 19, 2007, 04:30 #12
- Join Date
- Jun 2007
- Posts
- 15
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Hi Rajug
Thanks. Right now i just want to get everything working. I can follow alot of what's going on but not everything. eg can't figure oute where $newpicid is getting its info from
What i'd like to know is if i have a form that is uploading new images and saving them to the same folder you have named in your script 'uploads' how would i integrate it with your script.
Thankks for all your help
Katu
-
Jun 20, 2007, 17:20 #13
- Join Date
- Mar 2006
- Location
- Gold Coast, Australia
- Posts
- 1,369
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
thanks earl-grey that is a clear cut example of imagemagick's superiority... and thankyou rajug, this is the first bit of OOP that i've ever understood!
Studiotime - Time Management for Web Developers
to-do's, messages, invoicing, reporting - 30 day free trial!
Thomas Multimedia Web Development
Bookmarks