tamnic
asked on
PHP/GDlib Image Upload Script
Hi,
I am looking for a tutorial or a script that can do the below, I have found how-to's for each area I have described below but none show me how to place them together as a script. Any help would be appreciated.
Maybe someone has some script laying around which would meet the criteria I describe.
1.) I Will need the script in php; which will be using the GDlib.
2.) I need the script to Resize an Image and Create Thumbnails with Aspect Ratio.(will be stored in a BLOB)
3.) I need the script to convert gif,png,bmp into jpeg if needed, so when a user tries to upload an image this will convert automatically.
4.) Will need the code for uploading of 5 images(into mysql BLOB) at once to same id with different column name(image1,image2,etc...) .
5.) Also, need code to show the BLOB images(individually) for each id.
Thanks for your time,
I am looking for a tutorial or a script that can do the below, I have found how-to's for each area I have described below but none show me how to place them together as a script. Any help would be appreciated.
Maybe someone has some script laying around which would meet the criteria I describe.
1.) I Will need the script in php; which will be using the GDlib.
2.) I need the script to Resize an Image and Create Thumbnails with Aspect Ratio.(will be stored in a BLOB)
3.) I need the script to convert gif,png,bmp into jpeg if needed, so when a user tries to upload an image this will convert automatically.
4.) Will need the code for uploading of 5 images(into mysql BLOB) at once to same id with different column name(image1,image2,etc...)
5.) Also, need code to show the BLOB images(individually) for each id.
Thanks for your time,
ASKER
Well Actually I have never used a BLOB before was just wanting try something different when storing images
Thought this was an interesting way to learn more about mysql and its functionality.
Thought this was an interesting way to learn more about mysql and its functionality.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Wow, I wrote that show.php file a long time ago.
What version of php are you running?
My upload script uses mysqli so I'd need to make some changes if you are running <5.
What version of php are you running?
My upload script uses mysqli so I'd need to make some changes if you are running <5.
ASKER
Thanks landship your one of the Great Ones:)
I am running 5.
Thanks again,
I am running 5.
Thanks again,
You're welcome, you didn't have to award the points already, but give me a few days, and I'll have the full solution for you. Including updating the script for the show.php file.
I ran into a little problem since the gd library doesn't support .bmp images. I'm incorporating a function to make it work, but I won't have it done today. Just didn't want you to think I forgot.
ASKER
Thanks again appreciate your time
Here you go, just change the mysql info, and ask me if you have any questions:
*** sql for database table ***
CREATE TABLE `imageblob` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default '',
`image1` blob NOT NULL,
`image2` blob NOT NULL,
`image3` blob NOT NULL,
`image4` blob NOT NULL,
`image5` blob NOT NULL,
PRIMARY KEY (`id`)
)
*** class_photoAlbum.php ***
<?php
// Set the constants
define('MAX_WIDTH', '700');
define('MAX_HEIGHT', '700');
class photoAlbum {
function photoAlbum() {
} // End function photAlbum (constructor)
function addPhotos($db, $file, $post) {
$build_query = '';
for ($i = 0 ; $i < count($file['photo']['name ']) ; $i++) {
if (!is_uploaded_file(@$file[ 'photo'][' tmp_name'] [$i])) return 'The file was not uploaded properly.';
if (
(($file['photo']['type'][$ i] == 'image/jpeg') && ($image = @imagecreatefromjpeg($file ['photo'][ 'tmp_name' ][$i]))) ||
(($file['photo']['type'][$ i] == 'image/gif') && ($image = @imagecreatefromgif($file[ 'photo'][' tmp_name'] [$i]))) ||
(($file['photo']['type'][$ i] == 'image/png') && ($image = @imagecreatefrompng($file[ 'photo'][' tmp_name'] [$i]))) ||
(($file['photo']['type'][$ i] == 'image/bmp') && ($image = @$this->imagecreatefrombmp ($file['ph oto']['tmp _name'][$i ])))
) {} else { return 'This doesn’t seem to be a valid image type: <strong>'.$file['photo'][' type'][$i] .'</strong >'; }
if (!(list($width_orig, $height_orig) = getimagesize($file['photo' ]['tmp_nam e'][$i]))) return 'Can\'t calculate image size, please try again.';
// Max image dimensions
$ratio_orig = $width_orig/$height_orig;
$width = MAX_WIDTH;
$height = MAX_HEIGHT;
if (($width_orig < $width) && ($height_orig < $height)) return 'The image is too small and will look distorted';
if ($width/$height > $ratio_orig) {
$width = round($height*$ratio_orig) ;
} else {
$height = round($width/$ratio_orig);
}
$tmpName = urlencode($file['photo'][' name'][$i] );
// Resample and output
$image_p = imagecreatetruecolor($widt h, $height);
imagecopyresampled($image_ p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Catch image binary output
ob_start();
imagejpeg($image_p);
$img_output = ob_get_contents();
ob_end_clean();
$build_query .= ", image".($i+1)."='".addslas hes($img_o utput)."'" ;
// Cleanup
unlink($file['photo']['tmp _name'][$i ]);
} // End for i count(photo)
// Add the info to the database
$query = "insert into imageblob set name='".$db->real_escape_s tring($pos t['name']) ."'".$buil d_query;
if ($result = $db->query($query)) {
return true;
} else {
return $db->error;
}
} // End function addPhotos
function imagecreatefrombmp($filena me) {
/************************* ********** ********** /
/* Fonction: ImageCreateFromBMP */
/* Author: DHKold */
/* Contact: admin@dhkold.com */
/* Date: The 15th of June 2005 */
/* Version: 2.0B */
/************************* ********** ********** /
//Ouverture du fichier en mode binaire (Open file in binary mode)
if (! $f1 = fopen($filename,"rb")) return FALSE;
//1 : Chargement des ent?tes FICHIER (load the file)
$FILE = unpack("vfile_type/Vfile_s ize/Vreser ved/Vbitma p_offset", fread($f1,14));
if ($FILE['file_type'] != 19778) return FALSE;
//2 : Chargement des ent?tes BMP (load the bitmap)
$BMP = unpack('Vheader_size/Vwidt h/Vheight/ vplanes/vb its_per_pi xel/Vcompr ession/Vsi ze_bitmap/ Vhoriz_res olution/Vv ert_resolu tion/Vcolo rs_used/Vc olors_impo rtant', fread($f1,40));
$BMP['colors'] = pow(2,$BMP['bits_per_pixel ']);
if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel ']);
$BMP['decal'] = ($BMP['width']*$BMP['bytes _per_pixel ']/4);
$BMP['decal'] -= floor($BMP['width']*$BMP[' bytes_per_ pixel']/4) ;
$BMP['decal'] = 4-(4*$BMP['decal']);
if ($BMP['decal'] == 4) $BMP['decal'] = 0;
//3 : Chargement des couleurs de la palette (load the color palette)
$PALETTE = array();
if ($BMP['colors'] < 16777216) {
$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4 ));
}
//4 : Cr?ation de l'image (create the image)
$IMG = fread($f1,$BMP['size_bitma p']);
$VIDE = chr(0);
$res = imagecreatetruecolor($BMP[ 'width'],$ BMP['heigh t']);
$P = 0;
$Y = $BMP['height']-1;
while ($Y >= 0) {
$X=0;
while ($X < $BMP['width']) {
if ($BMP['bits_per_pixel'] == 24) {
$COLOR = unpack("V",substr($IMG,$P, 3).$VIDE);
} elseif ($BMP['bits_per_pixel'] == 16) {
$COLOR = unpack("n",substr($IMG,$P, 2));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} elseif ($BMP['bits_per_pixel'] == 8) {
$COLOR = unpack("n",$VIDE.substr($I MG,$P,1));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} elseif ($BMP['bits_per_pixel'] == 4) {
$COLOR = unpack("n",$VIDE.substr($I MG,floor($ P),1));
if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4); else $COLOR[1] = ($COLOR[1] & 0x0F);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} elseif ($BMP['bits_per_pixel'] == 1) {
$COLOR = unpack("n",$VIDE.substr($I MG,floor($ P),1));
if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >> 7;
elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} else return FALSE;
imagesetpixel($res,$X,$Y,$ COLOR[1]);
$X++;
$P += $BMP['bytes_per_pixel'];
}
$Y--;
$P+=$BMP['decal'];
}
//Fermeture du fichier (close the file)
fclose($f1);
return $res;
} // End function imagecreatefrombmp
} // End class photoAlbum
?>
*** form.php ***
<?php
if ($_SERVER['REQUEST_METHOD' ] != 'POST') {
?>
<form action="form.php" enctype="multipart/form-da ta" method="post">
<?php
for ($i = 0 ; $i < 5 ; $i++) {
?>
<p>Photo:<br /><input name="photo[]" type="file" /></p>
<?php
}
?>
<p>Name:<br /><input type="text" name="name" size="40" maxlength="80" /></p>
<p><input type="submit" name="submit" value="Add Image!" /></p>
</form>
<?php
} // End if form was not posted
else {
require_once('class_photoA lbum.php') ;
$album = new photoAlbum();
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$response = $album->addPhotos($db, $_FILES, $_POST);
if ($response === true) {
echo '<p>Images were uploaded</p>';
} else {
echo '<p>'.$response.'</p>';
}
}
?>
*** How to display the images ***
<img src="show.php?image=image1 &id=ROW_ID " />
*** show.php ***
<?php
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$query = "select ".$db->real_escape_string( $_GET['ima ge'])." from imageblob where id='".$db->real_escape_str ing($_GET[ 'id'])."'" ;
$result = $db->query($query);
$data = $result->fetch_assoc();
Header("Content-type: image/jpeg");
echo $data[$image];
?>
*** sql for database table ***
CREATE TABLE `imageblob` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default '',
`image1` blob NOT NULL,
`image2` blob NOT NULL,
`image3` blob NOT NULL,
`image4` blob NOT NULL,
`image5` blob NOT NULL,
PRIMARY KEY (`id`)
)
*** class_photoAlbum.php ***
<?php
// Set the constants
define('MAX_WIDTH', '700');
define('MAX_HEIGHT', '700');
class photoAlbum {
function photoAlbum() {
} // End function photAlbum (constructor)
function addPhotos($db, $file, $post) {
$build_query = '';
for ($i = 0 ; $i < count($file['photo']['name
if (!is_uploaded_file(@$file[
if (
(($file['photo']['type'][$
(($file['photo']['type'][$
(($file['photo']['type'][$
(($file['photo']['type'][$
) {} else { return 'This doesn’t seem to be a valid image type: <strong>'.$file['photo']['
if (!(list($width_orig, $height_orig) = getimagesize($file['photo'
// Max image dimensions
$ratio_orig = $width_orig/$height_orig;
$width = MAX_WIDTH;
$height = MAX_HEIGHT;
if (($width_orig < $width) && ($height_orig < $height)) return 'The image is too small and will look distorted';
if ($width/$height > $ratio_orig) {
$width = round($height*$ratio_orig)
} else {
$height = round($width/$ratio_orig);
}
$tmpName = urlencode($file['photo']['
// Resample and output
$image_p = imagecreatetruecolor($widt
imagecopyresampled($image_
// Catch image binary output
ob_start();
imagejpeg($image_p);
$img_output = ob_get_contents();
ob_end_clean();
$build_query .= ", image".($i+1)."='".addslas
// Cleanup
unlink($file['photo']['tmp
} // End for i count(photo)
// Add the info to the database
$query = "insert into imageblob set name='".$db->real_escape_s
if ($result = $db->query($query)) {
return true;
} else {
return $db->error;
}
} // End function addPhotos
function imagecreatefrombmp($filena
/*************************
/* Fonction: ImageCreateFromBMP */
/* Author: DHKold */
/* Contact: admin@dhkold.com */
/* Date: The 15th of June 2005 */
/* Version: 2.0B */
/*************************
//Ouverture du fichier en mode binaire (Open file in binary mode)
if (! $f1 = fopen($filename,"rb")) return FALSE;
//1 : Chargement des ent?tes FICHIER (load the file)
$FILE = unpack("vfile_type/Vfile_s
if ($FILE['file_type'] != 19778) return FALSE;
//2 : Chargement des ent?tes BMP (load the bitmap)
$BMP = unpack('Vheader_size/Vwidt
$BMP['colors'] = pow(2,$BMP['bits_per_pixel
if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel
$BMP['decal'] = ($BMP['width']*$BMP['bytes
$BMP['decal'] -= floor($BMP['width']*$BMP['
$BMP['decal'] = 4-(4*$BMP['decal']);
if ($BMP['decal'] == 4) $BMP['decal'] = 0;
//3 : Chargement des couleurs de la palette (load the color palette)
$PALETTE = array();
if ($BMP['colors'] < 16777216) {
$PALETTE = unpack('V'.$BMP['colors'],
}
//4 : Cr?ation de l'image (create the image)
$IMG = fread($f1,$BMP['size_bitma
$VIDE = chr(0);
$res = imagecreatetruecolor($BMP[
$P = 0;
$Y = $BMP['height']-1;
while ($Y >= 0) {
$X=0;
while ($X < $BMP['width']) {
if ($BMP['bits_per_pixel'] == 24) {
$COLOR = unpack("V",substr($IMG,$P,
} elseif ($BMP['bits_per_pixel'] == 16) {
$COLOR = unpack("n",substr($IMG,$P,
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} elseif ($BMP['bits_per_pixel'] == 8) {
$COLOR = unpack("n",$VIDE.substr($I
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} elseif ($BMP['bits_per_pixel'] == 4) {
$COLOR = unpack("n",$VIDE.substr($I
if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4); else $COLOR[1] = ($COLOR[1] & 0x0F);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} elseif ($BMP['bits_per_pixel'] == 1) {
$COLOR = unpack("n",$VIDE.substr($I
if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >> 7;
elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
} else return FALSE;
imagesetpixel($res,$X,$Y,$
$X++;
$P += $BMP['bytes_per_pixel'];
}
$Y--;
$P+=$BMP['decal'];
}
//Fermeture du fichier (close the file)
fclose($f1);
return $res;
} // End function imagecreatefrombmp
} // End class photoAlbum
?>
*** form.php ***
<?php
if ($_SERVER['REQUEST_METHOD'
?>
<form action="form.php" enctype="multipart/form-da
<?php
for ($i = 0 ; $i < 5 ; $i++) {
?>
<p>Photo:<br /><input name="photo[]" type="file" /></p>
<?php
}
?>
<p>Name:<br /><input type="text" name="name" size="40" maxlength="80" /></p>
<p><input type="submit" name="submit" value="Add Image!" /></p>
</form>
<?php
} // End if form was not posted
else {
require_once('class_photoA
$album = new photoAlbum();
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$response = $album->addPhotos($db, $_FILES, $_POST);
if ($response === true) {
echo '<p>Images were uploaded</p>';
} else {
echo '<p>'.$response.'</p>';
}
}
?>
*** How to display the images ***
<img src="show.php?image=image1
*** show.php ***
<?php
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$query = "select ".$db->real_escape_string(
$result = $db->query($query);
$data = $result->fetch_assoc();
Header("Content-type: image/jpeg");
echo $data[$image];
?>
Is there a reason you want the image stored in a blob instead of uploaded to a folder and reference the url from the database?