How to integrate php thumbnail creator with multiple image uploader script? - php

I have this code to upload multiple image. It is working fine.
<?php
include('db.php');
session_start();
$session_id='1'; //$session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$inputFileName = $_FILES['photoimg']['name'];
$actual_image_name = time().substr(str_replace(" ", "_", $ext), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
But I want to create thumbnail for per image. To do this I have another one. I have found it from a website...but I can't understand how to integrate with my original one.
function thumbnail($inputFileName, $maxSize = 100)
{
$info = getimagesize($inputFileName);
$type = isset($info['type']) ? $info['type'] : $info[2];
// Check support of file type
if ( !(imagetypes() & $type) )
{
// Server does not support file type
return false;
}
$width = isset($info['width']) ? $info['width'] : $info[0];
$height = isset($info['height']) ? $info['height'] : $info[1];
// Calculate aspect ratio
$wRatio = $maxSize / $width;
$hRatio = $maxSize / $height;
// Using imagecreatefromstring will automatically detect the file type
$sourceImage = imagecreatefromstring(file_get_contents($inputFileName));
// Calculate a proportional width and height no larger than the max size.
if ( ($width <= $maxSize) && ($height <= $maxSize) )
{
// Input is smaller than thumbnail, do nothing
return $sourceImage;
}
elseif ( ($wRatio * $height) < $maxSize )
{
// Image is horizontal
$tHeight = ceil($wRatio * $height);
$tWidth = $maxSize;
}
else
{
// Image is vertical
$tWidth = ceil($hRatio * $width);
$tHeight = $maxSize;
}
$thumb = imagecreatetruecolor($tWidth, $tHeight);
if ( $sourceImage === false )
{
// Could not load image
return false;
}
// Copy resampled makes a smooth thumbnail
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $tWidth, $tHeight, $width, $height);
imagedestroy($sourceImage);
return $thumb;
}
/**
* Save the image to a file. Type is determined from the extension.
* $quality is only used for jpegs.
* Author: mthorn.net
*/
function imageToFile($im, $fileName, $quality = 80)
{
if ( !$im || file_exists($fileName) )
{
return false;
}
$ext = strtolower(substr($fileName, strrpos($fileName, '.')));
switch ( $ext )
{
case '.gif':
imagegif($im, $fileName);
break;
case '.jpg':
case '.jpeg':
imagejpeg($im, $fileName, $quality);
break;
case '.png':
imagepng($im, $fileName);
break;
case '.bmp':
imagewbmp($im, $fileName);
break;
default:
return false;
}
return true;
}
$im = thumbnail('temp.jpg', 100);
imageToFile($im, 'temp-thumbnail.jpg');
Help will be greatly appreciated...

You can use following;
<?php
....
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
// Create thumbnail here
$thumb = thumbnail($path.$actual_image_name, "80"); // image name, and size
imageToFile($thumb, 'path/to/thumb/thumbnail_' . $session_id . '.jpg');
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
...
?>
Do not forget to add thumbnail and imageToFile to put in your php file

<?php
// thumbnail configuration
$thumb_width = 50;
$thumb_height = 50;
$thumb_method = 'crop';
$thumb_bgColour = null; //array(255,240,240);
$thumb_quality = 70;
// Let script run for as long as it needs to when creating thumbnails.
// Some web hosts won't let you use this function. In that case you'll need
// to comment it out and just refresh the script until it has thumbnailed all the images.
set_time_limit(0);
// include the thumbnail function
require_once dirname(__FILE__) . '/paGdThumbnail.php';
// get the path to the current directory
$path = dirname(__FILE__);
// get the url for the images
$path_info = pathinfo($_SERVER['SCRIPT_NAME']);
$url = $path_info['dirname'];
// create an array to store image names in.
$images = array();
//$dir = new DirectoryIterator($path);
$file_name=$_REQUEST['big_img'];//$_FILES['big_img']['name'];
$file_path=$path.'\\'.$file_name;
/*
Loop through the directory, finding all images that aren't thumbnails.
For each image:
- if it doesn't already have a thumbnail, or the thumbnail is older than the image,
create a thumbnail.
- get info about the image
- add the image to our images array
*/
if( preg_match('#^(.+?)(_t)?\.(jpg|gif|png)#i', $file_name, $matches)){
list( ,$name, $is_a_thumb, $extension) = $matches;
// if its not a thumbnail
if( !$is_a_thumb ){
// does a valid thumbnail exist?
$has_thumb = false;
$thumb_file = $path . '/' . $matches[1] . '_t.jpg';
if( file_exists($thumb_file) && filemtime($thumb_file) > filemtime($file_path) ){
$has_thumb = true;
}
else{
// no thumbnail, so we shall create one!
// create a gd image. reading the contents of the image file into a string, then
// using imagecreatefromstring saves having to check the filetype and which
// imagecreatefrom(jpeg/gif/png) function to use
$image = imagecreatefromstring(file_get_contents($file_path));
if( $image ){
// create the thumbnail
$thumb = paGdThumbnail($image, $thumb_width, $thumb_height, $thumb_method, $thumb_bgColour);
// free the image resource
imagedestroy($image);
if( $thumb ){
// save the thumbnail
if( imagejpeg($thumb, $thumb_file, $thumb_quality) ){
$has_thumb = true;
}
// free the memory used by the thumbnail image
imagedestroy($thumb);
}
}
}
if( $has_thumb ){
$images[$file_name] = $name;
}
}
}
// sort the images array so always in the same order
ksort($images);
// end or processing, now display the gallery
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Thumbnails :</title>
<style type="text/css">
<!--
#thumbs{
position: relative;
}
#thumbs div{
float: left;
width: <?php echo $thumb_width + 30?>px;
height: <?php echo $thumb_height + 30?>px;
text-align: center;
}
#thumbs a:link img, #thumbs a:visited img{
border: 1px solid #acacac;
padding: 5px;
}
#thumbs a:hover img{
border: 1px solid black;
}
-->
</style>
</head>
<body>
<div id="thumbs">
<?php foreach( $images as $imagename => $name ){ ?>
<div>
<img src="<?php echo $url . '/' . $name . '_t.jpg'?>" />
</div>
<?php }?>
</div>
</body>
</html>

Related

Image Gallery passing variables to header location doesnot working?

This below mentioned code is written localhost/uploads/gallery.php file. I am including it in another page so it can be a part of header and footer including all my styling. I did it by include('uploads/gallery.php'); into a div.
Everything is working fine except the header location. When I go to the page where gallery is included which is "localhost/index.php?page=media"(localhost/views/media.php). It does not display thumbnails. I have to refresh the page to see thumbnails. Note: the code is written to display thumbnails when they are generated without refreshing the page.
My concern for asking question is, why i have to refresh page to load thumbnails. My header location is not passing variables correctly. I am a complete noob. please help me with this. Shukriya.
<?php
if(isset($_GET['img'])){
if(file_exists("uploads/{$_GET['img']}")) {
ignore_user_abort(true);
set_time_limit(120);
ini_set('memory_limit', '256M');
$src_image = getimagesize("uploads/{$_GET['img']}");
var_dump($src_image);
if($src_image === false) {
die("Wrong Image");
} # Wrong File Size
// Fixed Thumbnail Size
$thumb_width = 144;
$thumb_height = 144;
$thumb_ratio = round (($thumb_width / $thumb_height), 1);
$src_ratio = round (($src_image[0] / $src_image[1]), 1);
if ($src_ratio > $thumb_ratio) {
//Landescape Image dynamic width...
$new_size = array(($src_image[0] * $thumb_height)/$src_image[1], $thumb_height);
$new_pos = array(($new_size[0] - $thumb_width)/2,0);
} elseif ($src_ratio < $thumb_ratio) {
//PORTRAIT Image dynamic Height.....
$new_size = array($thumb_width, ($src_image[1] * $thumb_width)/$src_image[0]);
$new_pos = array(0, ($new_size[1] - $thumb_height)/2);
} elseif($src_ratio == $thumb_ratio) {
//Square
$new_size = array($thumb_width, $thumb_height);
$new_pos = array(0, 0);
}
if($new_size[0] < 1) $new_size[0] = 1;
if($new_size[1] < 1) $new_size[1] = 1;
$imgz = 'uploads/thumbs/'.$_GET['img'];
//GETTING Variable for Source image type. to create resample
if($src_image['mime'] === "image/jpeg"){
$src = imagecreatefromjpeg('uploads/'.$_GET['img']);
} elseif($src_image['mime'] === "image/png"){
$src = imagecreatefrompng('uploads/'.$_GET['img']);
} elseif($src_image['mime'] === "image/gif"){
$src = imagecreatefromgif('uploads/'.$_GET['img']);
}
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
imagecopyresampled($thumb, $src, 0,0, $new_pos[0], $new_pos[1], $new_size[0], $new_size[1], $src_image[0], $src_image[1]);
//GETTING Variable for Destination thumb image type. to create resample
if($src_image['mime'] === "image/jpeg"){
imagejpeg($thumb, $imgz);
} elseif($src_image['mime'] === "image/png"){
imagepng($thumb, $imgz);
} elseif($src_image['mime'] === "image/gif"){
imagegif($thumb, $imgz);
}
header("Location: uploads/thumbs/{$_GET['img']}");
} /* If file exists */ die();
} // ALL SCRIPT ENDED
if(is_dir('uploads/thumbs') === false) {
mkdir('uploads/thumbs', 0744);
} // Check & Create Directory
$images = glob('uploads/'.'*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
foreach($images as $image){
$imgs = 'uploads/thumbs/'.substr($image,8);
$nme = substr($image,8);
if(file_exists("$imgs")){
echo "<img src=\"$imgs\" alt=\"$nme\" class=\"img-thumbnail\" />"; //uploads/{$img} , data-toggle=\"modal\" data-target=\"#myModal\"
} else {
echo "<img src=\"?page=media&img=$nme\" alt=\"$nme\" class=\"img-thumbnail\" />";
}
}
?>

Image resize in php?

How can i resize proportionaly image in php without "squishing" ? I need some solution, i was searching here, but i could't find anything what i need.
What i have:
<?php
if (isset($_SESSION['username'])) {
if (isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg', '.jpeg', '.png', '.gif');
$max_filesize = 10485760;
$upload_path = 'gallery/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if (!in_array($ext, $allowed_filetypes)) {
die('The file you attempted to upload is not allowed.');
}
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
die('The file you attempted to upload is too large.');
}
if (!is_writable($upload_path)) {
die('You cannot upload to the specified directory, please CHMOD it to 777.');
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
}
echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';
echo ' <input type="file" name="userfile"/>';
echo ' <input type="submit" name="upload" value="Качи">';
echo ' </form>';
} else {
echo "<font color='#ec3f8c'>Съжелявам! За да качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>";
}
?>
I want to add something like this:Click here
how i call images?
echo '<a href="profiles.php?id='.$rowtwo['id'].'">';
echo"<img src='gallery/".$rowtwo['avatar']."' width='170px' height='217px'/>";
echo'</a>';
I save my image of avatar in DB in users as avatar.
It's much easier to use JS. It also works better because you're letting the client do the slow work of manipulation vs using your finite server resources for that task.
Here's a sample:
//This is the URL to your original image
var linkUrl = "http://www.mywebsite.com/myimage.png";
//This is a div that is necessary to trick JS into letting you manipulate sizing
//Just make sure it exists and is hidden
var img = $('#HiddenDivForImg');
//This is a call to the function
image_GetResizedImage(img, linkUrl);
//This function does the magic
function image_GetResizedImage(img, linkUrl) {
//Set your max height or width dimension (either, not both)
var maxDim = 330;
//Define the equalizer to 1 to avoid errors if incorrect URL is given
var dimEq = 1;
//This determines if the larger dimension is the images height or width.
//Then, it divides that dimension by the maxDim to get a decimal number for size reduction
if (img.height() > maxDim || img.width() > maxDim) {
if (img.height() > img.width()) {
dimEq = maxDim / img.height();
} else {
dimEq = maxDim / img.width();
}
}
var imageOutput = "<a href='" + linkUrl + "' target='_blank'>View Larger</a><br /><a href='" + result +
"' target='_blank'><img src='" + linkUrl + "' style='width: " + img.width() * dimEq
+ "px; height: " + img.height() * dimEq + "px' /></a>";
//This returns a URL for the image with height and width tags of the resized (non-squished) image.
return imageOutput;
}
For image manipulation in PHP you can use Imagemagick.
http://www.imagemagick.org/
It's the scale command you are looking for.
Here I have created a function with your reference link, you can use it like this
Call it
//Resize uploaded image
resize_image($_FILES['userfile'], 100, 200);
//Or if you want to save image with diffrent name
$filename = $upload_path.$_SESSION['username'].'-avatar.jpg';
resize_image($_FILES['userfile'], 100, 200, $newfilename);
//if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$filename."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
Function
function resize_image($image_src, $w = 100, $h = 100, $save_as = null) {
// Create image from file
switch(strtolower($image_src['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($image_src['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($image_src['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($image_src['tmp_name']);
break;
default:
exit('Unsupported type: '.$image_src['type']);
}
// Target dimensions
$max_width = $w;
$max_height = $h;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
if($save_as) {
//Save as new file
imagejpeg($new, $save_as, 90);
}else{
//Overwrite image
imagejpeg($new, $image_src['tmp_name'], 90);
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
}
I use http://image.intervention.io/. You can scale, cache, store, convert and do various image manipulation tasks.
Very easy to use.
// load the image
$img = Image::make('public/foo.jpg');
// resize the width of the image to 300 pixels and constrain proportions.
$img->resize(300, null, true);
// save file as png with 60% quality
$img->save('public/bar.png', 60);

Image Processing - Upload/Resize/Create Thumb & Save

I'm looking for some help.
I have the following code which uploads the image & creates a thumbnail and stores them in the appropriate folders... But my problem is space.. the uploaded main images are HUGE 4320 x 3240 and the site takes ages to load...
I only want 2 images: A main image max width 1024, and a thumbnail max width 100....
UPDATE: Now works and resizes main image and creates thumbnail but only works on small image sizes < 2500px wide... but I need it to work on an image 4320px wide....
here's my code so far:
<?php ob_start();
session_start();
include("../../config.php");
ini_set("memory_limit", "500M");
$folder = "../images/stock/".$_SESSION['info_id']."";
$thumbs =$folder.'/thumbs/';
if(!file_exists($folder)){
mkdir ($folder,0777);
$uploadfolder = $folder."/";
//echo $folder.'<br>';
}
else
{
//echo 'folder already created<br>';
$uploadfolder = $folder."/";
//echo $folder.'<br>';
}
if(!file_exists($thumbs)){
mkdir($thumbs,0777);
$thumbnailfolder = $thumbs ;
//echo $thumbs.'<br>';
}else{
$thumbnailfolder = $thumbs ;
//echo $thumbnailfolder.'<br>';
}
$allowedfiletypes = array("jpeg","jpg");
//$uploadfolder = $s;
$thumbnailheight = 100; //in pixels
$imagesresizeheight = 500;
$action = $_POST['action'];
if ($action == "upload") {
//$_SESSION['result'] = "Uploading image... " ;
if(empty($_FILES['uploadimage']['name'])){
$_SESSION['result'] = "<strong>Error: File not uploaded 1!</strong><br>" ;
} else {
$uploadfilename = $_FILES['uploadimage']['name'];
$fileext = strtolower(substr($uploadfilename,strrpos($uploadfilename,".")+1));
if (!in_array($fileext,$allowedfiletypes)) { $_SESSION['result'] = "<strong>Error: Invalid file extension!</strong><br>" ; }
else {
$fulluploadfilename = $uploadfolder.$uploadfilename ;
if (move_uploaded_file($_FILES['uploadimage']['tmp_name'], $fulluploadfilename)) {
$im = imagecreatefromjpeg($fulluploadfilename);
if (!$im) { $_SESSION['result'] = "<p><strong>Error: Couldn't Resize Image!</strong><br>" ; }
else {
//// Resize Image Creation //////
$imw = imagesx($im); // uploaded image width
$imh = imagesy($im); // uploaded image height
$nh = $imagesresizeheight; // thumbnail height
$nw = round(($nh / $imh) * $imw); //thumnail width
$newim = imagecreatetruecolor ($nw, $nh);
imagecopyresampled ($newim,$im, 0, 0, 0, 0, $nw, $nh, $imw, $imh) ;
$imagefilename = $uploadfolder.$uploadfilename ;
imagejpeg($newim, $imagefilename) or die($_SESSION['result'] ="<strong>Error: Couldn't save image resize!</strong><br>");
echo $imw. $imh. $nw. $imagefilename;
//// Thumbnail Creation //////
$imw = imagesx($im); // uploaded image width
$imh = imagesy($im); // uploaded image height
$nh = $thumbnailheight; // thumbnail height
$nw = round(($nh / $imh) * $imw); //thumnail width
$newim = imagecreatetruecolor ($nw, $nh);
imagecopyresampled ($newim,$im, 0, 0, 0, 0, $nw, $nh, $imw, $imh) ;
$thumbfilename = $thumbnailfolder.$uploadfilename ;
imagejpeg($newim, $thumbfilename) or die($_SESSION['result'] ="<strong>Error: Couldn't save thumnbail!</strong><br>");
//echo $thumbfilename;
//$_SESSION['result'] ='<img src="'.$thumbfilename.'"/><br>' ;
}
} else { $_SESSION['result'] = "<strong>Error: Couldn't save file($fulluploadfilename)!</strong><br>";
}
}
}
}
//unlink($fulluploadfilename);
////////////////////////////////////////////////
//connect to mysql server
$c = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB);
if (!$c){
$_SESSION['result'] .= mysql_error().'<br>';
return;
}
if (!mysql_select_db(DB)){
$_SESSION['result'] .= mysql_error().'<br>';
mysql_close($c);
return;
}
//5. insert settings
$sql = "INSERT INTO photo(photo_id,photo_filename) VALUES ('".$_SESSION['info_id']."','".$uploadfilename."')";
if (!mysql_query($sql,$c)){
mysql_close($c);
return;
}
mysql_close($c);
//////////////////////////////////////////////
//$ref = getenv("HTTP_REFERER");
//header("Location: ".$ref);
?>
just
unlink($fulluploadfilename);
after all thumbnails are created.

How can insert 4 fileupload in one form

I need to know if is possible have in one form 4 fileupload, each one to save in different folder when a user want affiliate to our service.. like per example in first upload the Curriculum, next the photo and for the last two the diploma's..
Here is the form URL I am using right now and in "documentos" tab are all the input type file
here is my script
<?php
//----------------------------------------- start edit here ---------------------------------------------//
$script_location = "http://www.proderma.org/"; // location of the script
$maxlimit = 8388608; // maxim image limit
$folder = "uploads/foto_doc"; // folder where to save images
// requirements
$minwidth = 200; // minim width
$minheight = 200; // minim height
$maxwidth = 4608; // maxim width
$maxheight = 3456; // maxim height
$thumb3 = 1; // allow to create thumb n.3
// allowed extensions
$extensions = array('.png', '.gif', '.jpg', '.jpeg','.PNG', '.GIF', '.JPG', '.JPEG', '.docx');
//----------------------------------------- end edit here ---------------------------------------------//
// check that we have a file
if((!empty($_FILES["uploadfile"])) && ($_FILES['uploadfile']['error'] == 0)) {
// check extension
$extension = strrchr($_FILES['uploadfile']['name'], '.');
if (!in_array($extension, $extensions)) {
echo 'wrong file format, alowed only .png , .gif, .jpg, .jpeg
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else {
// get file size
$filesize = $_FILES['uploadfile']['size'];
// check filesize
if($filesize > $maxlimit){
echo "File size is too big.";
} else if($filesize < 1){
echo "File size is empty.";
} else {
// temporary file
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
// capture the original size of the uploaded image
list($width,$height) = getimagesize($uploadedfile);
// check if image size is lower
if($width < $minwidth || $height < $minheight){
echo 'Image is to small. Required minimum '.$minwidth.'x'.$minheight.'
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else if($width > $maxwidth || $height > $maxheight){
echo 'Image is to big. Required maximum '.$maxwidth.'x'.$maxheight.'
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else {
// all characters lowercase
$filename = strtolower($_FILES['uploadfile']['name']);
// replace all spaces with _
$filename = preg_replace('/\s/', '_', $filename);
// extract filename and extension
$pos = strrpos($filename, '.');
$basename = substr($filename, 0, $pos);
$ext = substr($filename, $pos+1);
// get random number
$rand = time();
// image name
$image = $basename .'-'. $rand . "." . $ext;
// check if file exists
$check = $folder . '/' . $image;
if (file_exists($check)) {
echo 'Image already exists';
} else {
// check if it's animate gif
$frames = exec("identify -format '%n' ". $uploadedfile ."");
if ($frames > 1) {
// yes it's animate image
// copy original image
copy($_FILES['uploadfile']['tmp_name'], $folder . '/' . $image);
} else {
// create an image from it so we can do the resize
switch($ext){
case "gif":
$src = imagecreatefromgif($uploadedfile);
break;
case "jpg":
$src = imagecreatefromjpeg($uploadedfile);
break;
case "jpeg":
$src = imagecreatefromjpeg($uploadedfile);
break;
case "png":
$src = imagecreatefrompng($uploadedfile);
break;
}
if ($thumb3 == 1){
// create third thumbnail image - resize original to 125 width x 125 height pixels
$newheight = ($height/$width)*600;
$newwidth = 600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagealphablending($tmp, false);
imagesavealpha($tmp,true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// write thumbnail to disk
$write_thumb3image = $folder .'/thumb3-'. $image;
switch($ext){
case "gif":
imagegif($tmp,$write_thumb3image);
break;
case "jpg":
imagejpeg($tmp,$write_thumb3image,100);
break;
case "jpeg":
imagejpeg($tmp,$write_thumb3image,100);
break;
case "png":
imagepng($tmp,$write_thumb3image);
break;
}
}
// all is done. clean temporary files
imagedestroy($src);
imagedestroy($tmp);
echo "<script language='javascript' type='text/javascript'>window.top.window.formEnable();</script>
<div class='clear'></div>";
}
}
}
}
// database connection
include('include/config.php');
$stmt = $conn->prepare('INSERT INTO INGRESOS (nombre,dui,nit,direccion,curriculum,pais,departamento,ciudad,telefono,email,universidad,diploma,jvpm,especializacion,diploma_esp,foto,website,contacto)
VALUES (:nombre,:dui,:nit,:direccion,:curriculum,:pais,:departamento,:ciudad,:telefono,:email,:universidad,:diploma,:jvpm,:especializacion,:diploma_esp,:foto,:website,:contacto)');
$stmt->execute(array(':nombre' => $nombre,':nit' => $nit,':direccion' => $direccion,':curriculum' => $path,':pais' => $pais,':departamento' => $departamento,':ciudad' => $ciudad,':departamento' => $departamento,':ciudad' => $ciudad,':telefono' => $telefono,':email' => $email,':universidad' => $universidad,':diploma' => $path1,':jvpm' => $jvpm,':especializacion' => $especializacion,':diploma_esp' => $path2,':foto' => $write_thumb3image,':website' => $website,':contacto' => $contacto));
echo 'Afiliación ingresada correctamente.';
$dbh = null;
}
// error all fileds must be filled
} else {
echo '<div class="wrong">You must to fill all fields!</div>'; }
?>
the files I need save only the path, so I have this:
:curriculum' => $path
:diploma' => $path1
:diploma_esp' => $path2
:foto' => $write_thumb3image
I don´t know if is possible these...I hope it can be.
Best Regards!
Include multiple file fields
<input type="file" name="file[0]" />
<input type="file" name="file[1]" />
<input type="file" name="file[2]" />
<input type="file" name="file[3]" />
Wrap a foreach around your save script
// set up your paths
$paths=array($path, $path1, $path2, $write_thumb3image);
// 0 1 2 3
// use them as your loop
foreach ($paths as $i=>$path){ // <- use an index $i
// *** save to $path.'/'.$your_image_name.$image_ext
// as Phillip rightly pointed out, $_FILES is different
// so using your index, pick out the bits from the $_FILES arary
$name=$_FILES['file']['name'][$i];
$type=$_FILES['file']['type'][$i];
$tmp_name=$_FILES['file']['tmp_name'][$i];
$size=$_FILES['file']['size'][$i];
$error=$_FILES['file']['error'][$i];
$extension = strrchr($name, '.'); // NB the file name does not mean that's the true extension
....
}
Untested

Image upload with resize

i have a upload script and that works fine, but i want that its upload twice, one orginal format and one in a thubm size.
I did allready search on google and stackoverflow and i tried allready something, but i dont get it work.
My upload script
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
include('./../includes/core.php');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Alleen '.implode(',',$allowed_ext).' bestanden zijn toegestaan');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
$name = $pic['name'];
$sname = hashing($name);
$datum = date("d-m-Y");
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$sname)){
mysql_query("INSERT INTO foto VALUES ('','".$pic['name']."','".$sname."', '".$datum."', '0')");
exit_status('Bestand succesvol geupload');
}
}
exit_status('Er is iets mis gegaan!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function hashing($naam){
$info = pathinfo($naam);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$hash = basename($naam, $ext);
$hash = $hash . genRandomstring();
$hash = md5($hash);
$hash = $hash . '-' . genRandomstring();
return $hash . $ext;
}
function genRandomString() {
$length = 5;
$string = "";
$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-+!#"; // change to whatever characters you want
while ($length > 0) {
$string .= $characters[mt_rand(0,strlen($characters)-1)];
$length -= 1;
}
return $string;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
If someone can help me? I will be very happy then becuase i have allready try this for a week and i can get it out.
Thanks, Chris
You have the image uploaded once, which is all you need, then use that to create the second thumbnail file.
Try looking over the GD documentation.
as mentioned before you don't need to upload twice, copy and resize image once it's uploaded like this:
$pathToImages = "path/to/images"
$pathToThumbs = "path/to/thumbs"
$fname = "image-file-name";
$new_fname = "thumb-file-name";
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
$thumbWidth = //someValue//;
$thumbHeight = //someValue//;
// calculate thumbnail size
$new_height = floor($height * ($thumbWidth/$width));
$new_width = $thumbWidth;
// create a new temporary image
$tmp_img = imagecreatetruecolor($thumbWidth, $thumbHeight);
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$new_fname}" );

Categories