Image resize in php? - 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);

Related

Multiple image upload by PHP and save all image's name in one row of a table in mysql

I have a php upload script which have 2 files to process uploaded image.
the first file contain html form and ajax script. this script work fine for uploading one image and save the image name and image patch to mysql table.
look at the codes:
Upload.php:
<?php
if($loggedin) {
$contents = "
<frame>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>Ajax Upload and Resize with jQuery and PHP - Demo</title>
<script type=\"text/javascript\" src=\"Images/js/jquery-1.10.2.min.js\"></script>
<script type=\"text/javascript\" src=\"Images/js/jquery.form.min.js\"></script>
<script type=\"text/javascript\">
$(document).ready(function() {
var progressbox = $('#progressbox');
var progressbar = $('#progressbar');
var statustxt = $('#statustxt');
var completed = '0%';
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
uploadProgress: OnProgress,
success: afterSuccess, // post-submit callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function() {
$(this).ajaxSubmit(options);
// return false to prevent standard browser submit and page navigation
return false;
});
//when upload progresses
function OnProgress(event, position, total, percentComplete)
{
//Progress bar
progressbar.width(percentComplete + '%') //update progressbar percent complete
statustxt.html(percentComplete + '%'); //update status text
if(percentComplete>50)
{
statustxt.css('color','#fff'); //change status text to white after 50%
}
}
//after succesful upload
function afterSuccess()
{
$('#submit-btn').show(); //hide submit button
$('#loading-img').hide(); //hide submit button
}
//function to check file size before uploading.
function beforeSubmit(){
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
if( !$('#imageInput').val()) //check empty input filed
{
$(\"#output\").html(\"Are you kidding me?\");
return false
}
var fsize = $('#imageInput')[0].files[0].size; //get file size
var ftype = $('#imageInput')[0].files[0].type; // get file type
//allow only valid image file types
switch(ftype)
{
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
break;
default:
$(\"#output\").html(\"<b>\"+ftype+\"</b> Unsupported file type!\");
return false
}
//Allowed file size is less than 1 MB (1048576)
if(fsize>8388608)
{
$(\"#output\").html(\"<b>\"+bytesToSize(fsize) +\"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.\");
return false
}
//Progress bar
progressbox.show(); //show progressbar
progressbar.width(completed); //initial value 0% of progressbar
statustxt.html(completed); //set status text
statustxt.css('color','#000'); //initial color of status text
$('#submit-btn').hide(); //hide submit button
$('#loading-img').show(); //hide submit button
$(\"#output\").html(\"\");
}
else
{
//Output error to older unsupported browsers that doesn't support HTML5 File API
$(\"#output\").html(\"Please upgrade your browser, because your current browser lacks some new features we need!\");
return false;
}
}
//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
</script>
<link href=\"Images/style/style.css\" rel=\"stylesheet\" type=\"text/css\">
</head>
<body>
<div id=\"upload-wrapper\">
<div align=\"center\">
<h3>Upload your Image</h3>
<span class=\"\">Image Type allowed: Jpeg, Jpg, Png and Gif. | Maximum Size 8 MB</span>
<form action=\"Process.php\" onSubmit=\"return false\" method=\"post\" enctype=\"multipart/form-data\" id=\"MyUploadForm\">
<input name=\"ImageFile\" id=\"imageInput\" type=\"file\" />
<input type=\"submit\" id=\"submit-btn\" value=\"Upload\" />
<img src=\"Images/images/ajax-loader.gif\" id=\"loading-img\" style=\"display:none;\" alt=\"Please Wait\"/>
</form>
<div id=\"progressbox\" style=\"display:none;\"><div id=\"progressbar\"></div ><div id=\"statustxt\">0%</div></div>
<div id=\"output\"></div>
</div>
</div>
</body>
</html>
</frame>
";
}else header("Location: login.php?return=upload.php");
?>
And, this file is for processing the submitted form:
Process.php:
<?php
if(isset($_POST))
{
############ Edit settings ##############
$ThumbSquareSize = 100; //Thumbnail will be 200x200
$BigImageMaxSize = 300; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = '/www/site/Images/uploads/'; //specify upload directory ends with / (slash)
$Quality = 90; //jpeg quality
##########################################
//check if this is an ajax request
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
die();
}
// check $_FILES['ImageFile'] not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
{
die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.
}
// Random number will be added after image name
$RandomNumber = rand(0, 9999999999999);
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name
$ImageSize = $_FILES['ImageFile']['size']; // get original image size
$TempSrc = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder
$ImageType = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
//Let's check allowed $ImageType, we use PHP SWITCH statement here
switch(strtolower($ImageType))
{
case 'image/png':
//Create a new image from file
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error and exit
}
//PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
//Get first two values from image, width and height.
//list assign svalues to $CurWidth,$CurHeight
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//Get file extension from Image name, this will be added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
//remove extension from filename
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
//Construct a new name with random number and extension.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
$NewThumbImageName = $ThumbPrefix.$NewImageName;
//set the Destination Image
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
$DestRandImageName = $DestinationDirectory.$NewImageName; // Image with destination directory
//Resize image to Specified Size by calling resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
/*
We have succesfully resized and created thumbnail image
We can now output image to user's browser or store information in the database
*/
// Insert info into database table!
$chkquery = mysql_query("SELECT * FROM `ID_Card` WHERE `UserName`='{$ir['username']}'")or die(mysql_error());
if(mysql_num_rows($chkquery) > 0){
while($chkquerys = #mysql_fetch_array($chkquery)){
$answer=$chkquerys['Approved'];
if($answer == 1) {
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"> some text:<br><br> <img src="'.$chkquerys['ImageName'].'" alt="Image"></td>';
echo '</tr>';
echo '</table>';
die();
}if($answer == 0) {
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"> some text:<br><br> <img src="'.$chkquerys['ImagePath'].''.$chkquerys['ImageName'].'" alt="Image"></td>';
echo '</tr>';
echo '</table>';
die();
}
}
} else{
/* DB Connect code goes here... */
mysql_query("INSERT INTO `Images`(Id,`UserName`,`ImageName`,`ThumbName`,`ImagePath`,`Approved`,`Ip`,`Date`)
VALUES (Null,'Null','$NewImageName','$NewThumbImageName','Images/uploads/','0','IP',unix_timestamp())")or die(mysql_error());}
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center">Dear '.$ir['username'].', your Image was uploaded successfully. please waiting for review and verify.</td>';
echo '</tr><tr>';
echo '<td align="center"><img src="Images/uploads/'.$NewImageName.'" alt="Resized Image"></td>';
echo '</tr>';
echo '</table>';
}else{
die('Resize Error'); //output error
}
}
// 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);
$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;
}
//Destroy image, frees memory
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;
}
//abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9
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;
}
//Destroy image, frees memory
if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
return true;
}
}
As I said this Script works prefect for one file...
But, how can I change it to work with 3 differents image field? (all fields are required.)
I want to upload 3 images and save all the uploaded image to one row of a table in database.
for example, I want to have these 3 fields in my form:
<label>Image #1:</label><input name="ImageFile1" type="file" >
<label>Image #2:</label><input name="ImageFile2" type="file" >
<label>Image #3:</label><input name="ImageFile3" type="file" >
after submitting the form, proccess.php upload files and save the name of images in one same row.
for example:
mysql_query("INSERT INTO `Images`(Id,`UserName`,`ImageName1`,`ImageName2`,`ImageName3`,`ImagePath`,`Approved`,`Ip`,`Date`)
VALUES (Null,'Null','$ImageName1','$ImageName2','$ImageName3','Images/uploads/','0','IP',unix_timestamp())")or die(mysql_error());}
Is that possible to do?
Thank you :)
Try setting the same name as an array such as:
<label>Image #1:</label><input name="ImageFile[]" type="file" >
<label>Image #2:</label><input name="ImageFile[]" type="file" >
<label>Image #3:</label><input name="ImageFile[]" type="file" >
Then you can loop the images like this (or pretty much like this):
$array = array();
foreach($_FILES['ImageFile'] as $img) {
// $img['name']
// $img['tmp']
// ...
// upload
// $array[] = {{the uploaded image}}
}
So now you can have as much images as you want. Put the result in an array ($array in that case) and just explode (or implode) like this: `explode(',',$array);
If you want a multiple image uploader, add the multiple in the input:
<label>Image #1:</label><input name="ImageFile[]" type="file" multiple="multiple">
This all works in my own codes, I just don't remember explode or implode, multiple="multiple" or multiple or multiple="true". You can Google that, though.

Upload and convert most common image types to png for fabric canvas background image

I'm trying to get this image uploading and converting script working correctly.
I had the script uploading any of the valid images and renaming them fine but then I added the conversion code and I can't get it working correctly. I commented out the // imagepng($image); because that caused the success div to fill with �PNG IHDR��G,�} IDATx���i���u'�s�]�%....... I've worked on this for two days looking at a lot of posts on Stack and thought I understood what was needed. If somebody could please look at this and maybe shed some light on my issue I would greatly appreciate it. In the current configuration I receive no errors on the server. Thanks!
PHP
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/include/session.php';
// Detect the file params according to need
$filename = $_FILES["myfile"]["name"];
$filesize = $_FILES["myfile"]["size"];
$tmp_name = $_FILES["myfile"]["tmp_name"];
$custnum = $session->custnum; //Users account number from session
// Valid extensions for Upload
$validExtensions = array('.jpeg', '.jpg', '.gif', '.png');
// Valid size in KB
$max_size = 6000;
// Detect file extension
$extension = strtolower(strrchr($filename, "."));
// Convert filesize in KB
$getFileSize = round($filesize / 1024, 1);
//Make the storage directory
if (!file_exists("maps/accounts/".$custnum)) {
mkdir("maps/accounts/".$custnum, 0777, true);
}
// Location to store the file
$path = str_replace('\/\\', '/', dirname(__FILE__)) . "/maps/accounts/".$custnum;
if( in_array($extension, $validExtensions) ){
if( $getFileSize < $max_size ){
if(is_dir($path)){
//***********Start of image conversion***********
$srcFile = $tmp_name;
list($width_orig, $height_orig, $type) = getimagesize($srcFile);
// Get the aspect ratio
$ratio_orig = $width_orig / $height_orig;
//Set max size
$width = 900;
$height = 600;
// resize to height (orig is portrait)
if ($ratio_orig < 1) {
$width = $height * $ratio_orig;
}
// resize to width (orig is landscape)
else {
$height = $width / $ratio_orig;
}
// Temporarily increase the memory limit to allow for larger images
ini_set('memory_limit', '32M');
switch ($type)
{
case IMAGETYPE_GIF:
$image = imagecreatefromgif($srcFile);
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($srcFile);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($srcFile);
break;
default:
throw new Exception('Unrecognized image type ' . $type);
}
// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagepng($newImage, $path . '/' . $custnum.'.png');
imagedestroy($image);
imagedestroy($newImage);
//******End of image conversion****************
// Success Message
echo "<div id='success' class='alert alert-success'><strong>Your map image was uploaded!</strong>
<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>
</div>";
} else {
trigger_errors("Directory not Found!<br /> $path");
}
} else {
$error_msg = "<strong>Filesize should be less then $max_size KB!</strong><br />Your file is about $getFileSize KB";
trigger_errors($error_msg);
}
} else {
$error_msg = "<strong>File not Supproted for Upload!</strong><br />
Please try with the files that has following extensions: .jpg, .jpeg, .gif, .png";
trigger_errors($error_msg);
}
// Make function that
// generate the Error
function trigger_errors( $error_msg ){
echo "<div class='alert alert-error'>
<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>
$error_msg
</div>";
}
?>
Here's my JQuery Ajax script that is iside the fabric.js kitchensink.js that's calling the above php script.
JQuery Ajax
$('#loading').hide();
$(function(){
var $form = $('#myform'),
$result = $('#result');
$('form').on('change','#myfile', function(){
$('#loading').show();
$result.ajaxStart(function(){
});
$form.ajaxForm({
target: $result
}).submit();
$( document ).ajaxComplete(function() {
$('#loading').delay(1500).hide('slow');
if ($('#success').hasClass('alert-success')){
canvas.setBackgroundImage(fullurl , function() {
canvas.renderAll();
});};
});
});
})
Here's my current html that calls the Ajax and php image processor. This html receives the feed back from the php and ajax success or failure to give feedback to the user.
HTML
<div>
<form id="myform" action="image_uploader.php" method="post" enctype="multipart/form-data">
<table align="center">
<tr>
<td width="100"><label>Select File: </label></td>
<td>
<input class="btn shape" type="file" id="myfile" name="myfile">
</td>
</tr>
</table>
</form>
<div id="loading"><img src="fabric/img/loadingbar.gif" width="200" height="15" alt="" border="0"><img src="fabric/img/uploading-text.GIF" width="128" height="19" alt="" border="0"></div>
</div>
<div id="result"></div>
You don't need to call move_uploaded_file actually. In fact, you'll not get the results you want if you do.
// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagepng($newImage, $path . '/' . $custnum);
imagedestroy($image);
imagedestroy($newImage);
The reason you'll want to do this is that the second argument of imagepng can be a path to save the file. Since you've gone to all the trouble of converting the file, calling move_uploaded_file will move the original file into a png filename. So if I upload a JPEG with your script it would move that JPEG into example.png. In other words, it wouldn't be a PNG, it would still be a JPEG.
The reason it's dumping the way you're written is that, without that path, the function returns the raw image so your browser is trying to interpret that binary data as text and, thus, you get gibberish and random characters.
You are just moving the uploaded file..
So.. Remove this line..
header('Content-Type: image/png');

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

Renaming Files by adding a Suffix

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.

how to modify this php script to handle png and gif uploads

I have the following script (it looks long, but well commented). Problem is, i get errors when i try to upload a png or gif image. What can i do to adjust this (easy if possible) so that it can either work with png's and gif's or convert them before trying to work with them.
This is the error that i recieve
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
Aparently the first part of the script is working, saving the original upload, but how should i go about this?
$idir = "images/"; // Path To Images Directory
$tdir = "images/"; // Path To Thumbnails Directory
$twidth = "125"; // Maximum Width For Thumbnail Images
$theight = "100"; // Maximum Height For Thumbnail Images
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$simg = imagecreatefromjpeg("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}
Any guidance here is greatly appreciated.
Well, imagecreatefromjpeg() can only create images from... jpegs. There are sister functions for creating images from other file types, namely imagecreatefrompng() and imagecreatefromgif().
I've added to your code. Give it a try. Make sure you see the changes, as I put a die() in there in case of an invalid image, which may not be what you want:
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$cfunction = 'imagecreatefromjpeg';
if ($_FILES['imagefile']['type'] == "image/png") {
$cfunction = 'imagecreatefrompng';
} else if ($_FILES['imagefile']['type'] == "image/gif") {
$cfunction = 'imagecreatefromgif';
} else {
die("Invalid image format.");
}
$simg = $cfunction("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}

Categories