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
Related
i'm a php newbie and still trying to get to grips with the language.
I need to crop the images i'm uploading into squares using php. Here is my current code to upload the images (which is working fine):
<?php
error_reporting(0);
$sUploadDirectory = 'uploads/';
$aFileTypesAllowed = array('image/jpeg', 'image/gif', 'image/png');
$aExtensionsAllowed = array('gif', 'png', 'jpg', 'jpeg');
$aJSExtensions = 'new Array("gif", "png", "jpg", "jpeg")';
$bImagesOnly = true;
$iMaxFileSize = 102400;
if(isset($_REQUEST['upload']) && $_REQUEST['upload'] == 'true') {
$bSuccess = true;
$sErrorMsg = 'Your image was successfully uploaded.';
if (array_search($_FILES['myFile']['type'], $aFileTypesAllowed) === false ||
!in_array(end(explode('.', strtolower($_FILES['myFile']['name']))), $aExtensionsAllowed)) {
$bSuccess = false;
$sErrorMsg = 'Invalid file format. Acceptable formats are: ' . implode(', ', $aFileTypesAllowed);
} else if ($bImagesOnly && !(getimagesize($_FILES['myFile']['tmp_name']))) {
$bSuccess = false;
$sErrorMsg = 'The image is invalid or corrupt. Please select another.';
} else if ($_FILES['myFile']['size'] > $iMaxFileSize) {
$bSuccess = false;
$sErrorMsg = 'The file size of your property photo must not exceed ' . ($iMaxFileSize / 1024) . 'Kb. Please try again.';
} else {
if (!#move_uploaded_file($_FILES['myFile']['tmp_name'], $sUploadDirectory . $_FILES['myFile']['name'])) {
$bSuccess = false;
$sErrorMsg = 'An unexpected error occurred while saving your uploaded photo. Please try again.';
}
}
print '<html>' .
'<head>' .
'<script type="text/javascript">' .
'parent.uploadResult(' . ($bSuccess ? 'true' : 'false') . ', \'' . $sErrorMsg . '\', \'' . $sUploadDirectory . $_FILES['myFile']['name'] . '\');' .
'</script>' .
'</head>' .
'<body></body>' .
'</html>';
die();
}
?>
I've tried adding this after the last argument checking the file size, it works on desktop, however doesn't on mobile when you use the 'take photo' option, which is an essential option in my design:
//*********************
//crop image into sqaure
//**********************
// Original image
$filename = $_FILES['myFile']['tmp_name'];
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = $current_width / 2 - 320;
$top = $current_height / 2 - 320;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 640;
$crop_height = 640;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width,
$current_height);
imagejpeg($canvas, $filename, 100);
//*********************
//crop image into sqaure
//**********************
I'm wondering if I have coded this poorly causing it not to work,
If any one could help i'd be very grateful! Thanks!
so this is the code that works on desktop but not on mobile, the first html entry above works on mobile and desktop.
<?php
error_reporting(0);
$sUploadDirectory = 'uploads/';
$aFileTypesAllowed = array('image/jpeg', 'image/gif', 'image/png');
$aExtensionsAllowed = array('gif', 'png', 'jpg', 'jpeg');
$aJSExtensions = 'new Array("gif", "png", "jpg", "jpeg")';
$bImagesOnly = true;
$iMaxFileSize = 4194304;
if(isset($_REQUEST['upload']) && $_REQUEST['upload'] == 'true') {
$temp = explode(".", $_FILES["myFile"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$bSuccess = true;
$sErrorMsg = 'Thanks! Your image was successfully uploaded.';
if (array_search($_FILES['myFile']['type'], $aFileTypesAllowed) === false ||
!in_array(end(explode('.', strtolower($_FILES['myFile']['name']))), $aExtensionsAllowed)) {
$bSuccess = false;
$sErrorMsg = 'Invalid file format. Acceptable formats are: ' . implode(', ', $aFileTypesAllowed);
} else if ($bImagesOnly && !(getimagesize($_FILES['myFile']['tmp_name']))) {
$bSuccess = false;
$sErrorMsg = 'The image is invalid or corrupt. Please select another.';
} else if ($_FILES['myFile']['size'] > $iMaxFileSize) {
$bSuccess = false;
$sErrorMsg = 'The file size of your property photo must not exceed ' . ($iMaxFileSize / 1024) . 'Kb. Please try again.';
} else {
$filename = $_FILES['myFile']['tmp_name'];
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = $current_width / 2 - ($current_width / 2);
$top = $current_height / 2 - ($current_width / 2);
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = $current_width;
$crop_height = $current_width;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
if (!#move_uploaded_file($_FILES['myFile']['tmp_name'], $sUploadDirectory . $newfilename)) {
$bSuccess = false;
$sErrorMsg = 'An unexpected error occurred while saving your uploaded photo. Please try again.';
}
}
print '<html>' .
'<head>' .
'<script type="text/javascript">' .
'parent.uploadResult(' . ($bSuccess ? 'true' : 'false') . ', \'' . $sErrorMsg . '\', \'' . $sUploadDirectory . $newfilename . '\');' .
'</script>' .
'</head>' .
'<body></body>' .
'</html>';
die();
}
?>
You can use the native PHP function imagecrop.
The following code will cut anything that is not a square (if the aspect ratio is greater or less than 1).
Of course, this is a little bit thrown together and could absolutely be a little bit more optimized, but it will do for now.
// Uploaded file temporary location
$fileTemp = $_FILES["myFile"]["tmp_name"];
// Validate the file extension.
$fileExt = strtolower(end(explode(".", $_FILES["myFile"]["name"])));
switch($fileExt){
case "jpg":
case "jpeg":
$image = imagecreatefromjpeg($fileTemp);
break;
case "png":
$image = imagecreatefrompng($fileTemp);
break;
case "gif":
$image = imagecreatefromgif($fileTemp);
break;
default:
$errorMessage = "Invalid file format. Acceptable formats are: " . implode(", ", $validFileTypes);
}
// Retrieve image resolution and aspect ratio.
list($width, $height) = getimagesize($fileTemp);
$aspectRatio = $width / $height;
// Crop the image based on the provided aspect ratio.
if($aspectRatio !== 1){
$portrait = $aspectRatio < 1;
// This will check if the image is portrait or landscape and crop it square accordingly.
$image = imagecrop($image, [
"x" => $portrait ? 0 : (($width - $height) / 2),
"y" => $portrait ? (($width - $height) / 2) : 0,
"width" => $portrait ? $width : $height,
"height" => $portrait ? $width : $height
]);
}
// Constrain max file size.
$maxFileSize = 102400;
if($_FILES["myFile"]["size"] >= $maxFileSize){
$errorMessage = "The file size of your property photo must not exceed " . ($maxFileSize / 1024) . "Kb. Please try again.";
}
// Send to CDN...
if(empty($errorMessage)){
}
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);
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>
I'm really new to joomla, I don't have idea what should I do to make it done. I just have this kind of code in administrator table, it refers to uploading files.
//Support for file field: cover
if(isset($_FILES['jform']['name']['cover'])):
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.file');
$file = $_FILES['jform'];
//Check if the server found any error.
$fileError = $file['error']['cover'];
$message = '';
if($fileError > 0 && $fileError != 4) {
switch ($fileError) :
case 1:
$message = JText::_( 'File size exceeds allowed by the server');
break;
case 2:
$message = JText::_( 'File size exceeds allowed by the html form');
break;
case 3:
$message = JText::_( 'Partial upload error');
break;
endswitch;
if($message != '') :
JError::raiseWarning(500,$message);
return false;
endif;
}
else if($fileError == 4){
if(isset($array['cover_hidden'])):;
$array['cover'] = $array['cover_hidden'];
endif;
}
else{
//Check for filesize
$fileSize = $file['size']['cover'];
if($fileSize > 10485760):
JError::raiseWarning(500, 'File bigger than 10MB' );
return false;
endif;
//Replace any special characters in the filename
$filename = explode('.',$file['name']['cover']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
//Add Timestamp MD5 to avoid overwriting
$filename = md5(time()) . '-' . implode('.',$filename);
$uploadPath = JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_comic'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.$filename;
$fileTemp = $file['tmp_name']['cover'];
if(!JFile::exists($uploadPath)):
if (!JFile::upload($fileTemp, $uploadPath)):
JError::raiseWarning(500,'Error moving file');
return false;
endif;
endif;
$array['cover'] = $filename;
}
endif;
I could upload the file (in this case, an image) from the codes above, but what I'll do next is creating a thumbnail for the uploaded image. I searched for the php codes through the internet but it doesn't seem to work since I can't synchronize it into joomla codes. Umm.. I've made a folder named thumbnail in images folder. So what should I do next?
I'll be so happy and grateful if any of you could help me with this. Thanks.
Well i can share technique I'm using, i hope it will help:
In table's method check after the all validation is done (at the end of the method, just before returning true) i add the following code:
$input = JFactory::getApplication()->input;
$files = $input->files->get('jform');
if (!is_null($files) && isset($files['image']))
$this->image = $this->storeImage($files['image']);
The i create a new method called storeImage() :
protected $_thumb = array('max_w' => 200, 'max_h' => 200);
private function storeImage($file) {
jimport('joomla.filesystem.file');
$filename = JFile::makeSafe($file['name']);
$imageSrc = $file['tmp_name'];
$extension = strtolower(JFile::getExt($filename));
// You can add custom images path here
$imagesPath = JPATH_ROOT . '/media/';
if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {
// Generate random filename
$noExt = rand(1000, 9999) . time() . rand(1000, 9999);
$newFilename = $noExt . '.' . $extension;
$imageDest = $imagesPath . $newFilename;
if (JFile::upload($imageSrc, $imageDest)) {
// Get image size
list($w, $h, $type) = GetImageSize($imageDest);
switch ($extension) {
case 'jpg':
case 'jpeg':
$srcRes = imagecreatefromjpeg($imageDest);
break;
case 'png':
$srcRes = imagecreatefrompng($imageDest);
break;
case 'gif':
$srcRes = imagecreatefromgif($imageDest);
break;
}
// Calculating thumb size
if($w > $h) {
$width_ratio = $this->_thumb['max_w'] / $w;
$new_width = $this->_thumb['max_w'];
$new_height = $h * $width_ratio;
} else {
$height_ratio = $this->_thumb['max_w'] / $h;
$new_width = $w * $height_ratio;
$new_height = $this->_thumb['max_w'];
}
$destRes = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($destRes, $srcRes, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Creating resized thumbnail
switch ($extension) {
case 'jpg':
case 'jpeg':
imagejpeg($destRes, $imagesPath . 'thumb_' . $newFilename, 100);
break;
case 'png':
imagepng($destRes, $imagesPath . 'thumb_' . $newFilename, 1);
break;
case 'gif':
imagegif($destRes, $imagesPath . 'thumb_' . $newFilename, 100);
break;
}
imagedestroy($destRes);
// Delete old image if it was set before
if (($this->image != "") && JFile::exists($imagesPath . $this->image)) {
JFile::delete($imagesPath . $this->image);
JFile::delete($imagesPath . 'thumb_' . $this->image);
}
return $newFilename;
}
}
}
}
return null;
}
This method returns uploaded file filename, which table stores in 'image' column. It creates two files, one original image and resized thumb with file prefix '_thumb'.
I hope it helps :)
I used Jimage : https://api.joomla.org/cms-3/classes/JImage.html
$JImage = new JImage($img_path);
$size_thumb = '150x150';
$JImage->createThumbs($size_thumb,1,$path.'/thumb');
Short, simple and efficient.
Can i change the name of the file, say an image for example which has name like '0124.jpg',
before sending it to the server?
<input id="f1" style="margin-bottom: 5px;" type="file" name="f1" onchange="javascript:readURL_f1(this);"/>
<input id="f2" style="margin-bottom: 5px;" type="file" name="f1" onchange="javascript:readURL_f2(this);"/>
If the file is uploaded from f1, then before sending to to server, the name should become pic1_[filename].jpg, instead of just sending the raw filename.
I don't want this to be done in server side because i think it might be complicated.
EDIT : Upload.php is my php file which uploads whatever in the file. So, its been a challenge for me. i can change the filename, but that gets changed in all the three uploads.
for example i add an '_' for the incoming filename. Then, it gets changed to all filenames.
Anyway from clientside?
my upload script: Upload.php
upload.php
<?php mysql_connect('localhost','root','phpmyadmin');
$connected = mysql_select_db('image_Upload');
?>
<noscript>
<div align="center">Go Back To Upload Form</div><!-- If javascript is disabled -->
</noscript>
<?php
//If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini
//Some Settings
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$BigImageMaxSize = 500; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = 'uploads/'; //Upload Directory ends with / (slash)
$Quality = 90;
$id = 'm123';
//ini_set('memory_limit', '-1'); // maximum memory!
foreach($_FILES as $file)
{
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];
if (is_array($ImageName))
{
$c = count($ImageName);
echo '<ul>';
for ($i=0; $i < $c; $i++)
{
$processImage = true;
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
}
else
{
//Validate file + create image from uploaded file.
switch(strtolower($ImageType[$i]))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($TempSrc[$i]);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($TempSrc[$i]);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
break;
default:
$processImage = false; //image format is not supported!
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.','',$ImageExt);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $id.'_'.'pic'.($i+1).'.'.$ImageExt;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
//Get New Image Size
list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="uploads/'.$ThumbPrefix.$NewImageName.
'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="uploads/'.$NewImageName.
'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>';
echo '</tr>';
echo '</table>';
if(isset($id))
{
mysql_query("UPDATE imagetable SET ImageName='$DestRandImageName',ThumbName='$thumb_DestRandImageName',
ImgPath='uploads/' WHERE id='$id'");
}
else{
mysql_query("INSERT INTO imagetable (id, ImageName, ThumbName, ImgPath)
VALUES ('$id','$DestRandImageName', '$thumb_DestRandImageName', 'uploads/')");
}
}else{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName.
'</strong>! Please check if file is supported</div>';
}
}
}
echo '</ul>';
}
}
// This function will proportionally resize image
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
//Construct a proportional size of new image
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
{
$NewWidth = $CurWidth;
$NewHeight = $CurHeight;
}
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
if($CurWidth>$CurHeight)
{
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
When you are uploading the File you usually follow this workflow
User Chooses a File and Clicks Upload
Server Pics up the File from the temp folder - check MimeType, Resize and Rename the File and store it to which ever location you want on the file server.
While Renaming if you want to see if the same file name exsists and then append the _01, _02 then you will have to check if a file exists with that name and then append the unique number at the end.
Things like that are usually done in the server side. The purpose of preppending or appending a code or, say, changing the whole name of the file is to prevent uploaded file name conflicts. So imagine doing it to the client side? When upload button is pressed you need to ask the server if this file name is already existing, then you wait for the response of the server then do the renaming based on the response then send it to the server instead of just sending it to the server then do the checking then renaming then saving.