I have a number of upload file forms that need validating (shortened example):
<form>
<input type='file' name='file[]' class='file_upload_button'>
<input type='file' name='file[]' class='file_upload_button'>
<input type='file' name='file[]' class='file_upload_button'>
<input type='file' name='file[]' class='file_upload_button'>
<input type='submit' value='Save Draft' class='save_draft_button'>
</form>
And I want each upload input to be validated by file type, but I'm having a hard to understanding what needs to be done. This is the kind of thing I'm trying, but evidently it's not right!
if (! empty($_FILES['file']['name'][0])) {
// VALIDATION goes here
}
But I can't figure out how to select, for example, the first upload field - I've tried using $_FILES['file']['name'][0] but to no avail. Any hep would be appreciated!
By chance, I wrote the following script yesterday.
This is for resizing images, PNG or GIF or JPEG.
This requires './tmp' directory.
If you like, please refer to this.
<?php
$html = PHP_EOL;
if (!empty($_FILES['images'])) {
$finfo = new finfo(FILEINFO_MIME);
for ($i=0;;$i++) {
switch (true) {
case (!isset($_FILES['images']['tmp_name'][$i])):
break 2;
case (!is_uploaded_file($filename = $_FILES['images']['tmp_name'][$i])):
case (($type = $finfo->file($filename)) === false):
continue 2;
case ($type === 'image/png; charset=binary'):
$img = imagecreatefrompng($filename);
break;
case ($type === 'image/jpeg; charset=binary'):
$img = imagecreatefromjpeg($filename);
break;
case ($type === 'image/gif; charset=binary'):
$img = imagecreatefromgif($filename);
break;
default:
continue 2;
}
list($width, $height) = getimagesize($filename);
$new_width = 100;
$new_height = (int)($new_width * $height / $width);
$new_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled(
$new_img, $img,
0, 0, 0, 0,
$new_width, $new_height, $width, $height
);
switch (true) {
case ($type === 'image/png; charset=binary'):
imagepng($new_img, $filename);
break;
case ($type === 'image/jpeg; charset=binary'):
imagejpeg($new_img, $filename);
break;
default:
imagegif($new_img, $filename);
}
$new_filename = './tmp/'.basename($filename);
if (move_uploaded_file($filename,$new_filename))
$html .= sprintf('<p><img src="%s" /></p>'.PHP_EOL, $new_filename);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Resizer</title>
<style>
label { display: block; }
</style>
</head>
<body>
<fieldset>
<legend>Select Image File (PNG, JPEG, GIF available)</legend>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<label><input type="file" name="images[]" /></label>
<label><input type="file" name="images[]" /></label>
<label><input type="file" name="images[]" /></label>
<label><input type="submit" value="Resize!" /></label>
</form>
</fieldset>
<fieldset>
<legend>Resized Images</legend><?php
echo $html;
?>
</fieldset>
</body>
</html>
Related
I am trying to make an avatar image upload for user, where they can crop the avatar too. At this moment I'm able to save the normal size of the image on my server, but when I am trying to crop that image it's like the coordinates are fixed, I think on the left top corner.
Here is my form in accounts.php:
<a href="#" data-toggle="modal" data-target="#change-profile">
<div id="profile-result">
<?php if (file_exists('accounts/images/' . $session_username . '.jpg')): ?>
<img src="<?php echo 'accounts/images/' . $session_username . '.jpg'; ?>" alt="" class="thumb-lg img-circle" style="width: 120px; height: 120px;">
<?php else: ?>
<img src="accounts/images/default.png" alt="" class="thumb-lg img-circle" style="width: 120px; height: 120px;">
<?php endif ?>
</div>
</a>
<div class="modal fade" id="change-profile">
<div class="modal-dialog">
<div class="" style="background: #fff; padding: 10px;">
<div class="ajax-response" id="loading"></div>
<h4 class="m-t-5 m-b-5 ellipsis">Change profile</h4>
<div class="image-full-div" style="width: 70%;">
<form action="crop.php" enctype="multipart/form-data" method="post" onsubmit="return checkCoords();">
<p>Image: <input name="image" id="fileInput" type="file" /></p>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input name="upload" type="submit" value="Upload" />
</form>
<p><img id="filePreview" style="display:none;"/></p>
</div>
</div>
</div>
</div>
This is my crop.php file for the upload:
<?php
//if upload form is submitted
if(isset($_POST["upload"])){
//get the file information
$error = '';
$fileName = basename($_FILES["image"]["name"]);
$fileTmp = $_FILES["image"]["tmp_name"];
$fileType = $_FILES["image"]["type"];
$fileSize = $_FILES["image"]["size"];
$fileExt = substr($fileName, strrpos($fileName, ".") + 1);
//specify image upload directory
$largeImageLoc = 'accounts/images/'.$fileName;
$thumbImageLoc = 'accounts/images/thumb/'.$fileName;
//check file extension
if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)){
if($fileExt != "jpg" && $fileExt != "jpeg" && $fileExt != "png"){
$error = "Sorry, only JPG, JPEG & PNG files are allowed.";
}
}else{
$error = "Select a JPG, JPEG & PNG image to upload";
}
//if everything is ok, try to upload file
if(strlen($error) == 0 && !empty($fileName)){
if(move_uploaded_file($fileTmp, $largeImageLoc)){
//file permission
chmod ($largeImageLoc, 0777);
//get dimensions of the original image
list($width_org, $height_org) = getimagesize($largeImageLoc);
//get image coords
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$width = (int) $_POST['w'];
$height = (int) $_POST['h'];
//define the final size of the cropped image
$width_new = $width;
$height_new = $height;
//crop and resize image
$newImage = imagecreatetruecolor($width_new,$height_new);
switch($fileType) {
case "image/gif":
$source = imagecreatefromgif($largeImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source = imagecreatefromjpeg($largeImageLoc);
break;
case "image/png":
case "image/x-png":
$source = imagecreatefrompng($largeImageLoc);
break;
}
imagecopyresampled($newImage,$source,0,0,$x,$y,$width_new,$height_new,$width,$height);
switch($fileType) {
case "image/gif":
imagegif($newImage,$thumbImageLoc);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumbImageLoc,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumbImageLoc);
break;
}
imagedestroy($newImage);
//remove large image
//unlink($imageUploadLoc);
//display cropped image
echo 'CROP IMAGE:<br/><img src="'.$thumbImageLoc.'"/>';
}else{
$error = "Sorry, there was an error uploading your file.";
}
}else{
//display error
echo $error;
}
}
?>
And my Javascript file:
//set image coordinates
function updateCoords(im,obj){
$('#x').val(obj.x1);
$('#y').val(obj.y1);
$('#w').val(obj.width);
$('#h').val(obj.height);
}
//check coordinates
function checkCoords(){
if(parseInt($('#w').val())) return true;
alert('Please select a crop region then press submit.');
return false;
}
$(document).ready(function(){
//prepare instant image preview
var p = $("#filePreview");
$("#fileInput").change(function(){
//fadeOut or hide preview
p.fadeOut();
//prepare HTML5 FileReader
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("fileInput").files[0]);
oFReader.onload = function (oFREvent) {
p.attr('src', oFREvent.target.result).fadeIn();
};
});
//implement imgAreaSelect plugin
$('img#filePreview').imgAreaSelect({
// set crop ratio (optional)
//aspectRatio: '2:1',
onSelectEnd: updateCoords
});
});
This is my image with the coordinates but I'm not sure because the normal size of the image is 1920/1080
And this image is after I press upload button
Im using the following PHP code to save a cropped image from jcrop.
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = "../profiles/";
$src = $target . basename( $_FILES['userfile']['name']);
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
imagejpeg($dst_r, "simple2.jpg", $jpeg_quality);
A simple2.jpg does get saved in the directory, but it is just a black colored square of size 2 KB. I want the cropped part to be saved. How to fix this?
Use this
index.php
<html lang="en" >
<head>
<meta charset="utf-8" />
<meta name="author" content="Script Tutorials" />
<title>HTML5 Image uploader with Jcrop | Script Tutorials</title>
<!-- add styles -->
<link href="css/main.css" rel="stylesheet" type="text/css" />
<link href="css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />
<!-- add scripts -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<header>
<h2>HTML5 Image uploader with Jcrop </h2>
</header>
<div class="demo">
<div class="bheader"><h2>-- Image upload form --</h2></div>
<div class="bbody">
<!-- upload form -->
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">
<!-- hidden crop params -->
<input type="hidden" id="x1" name="x1" />
<input type="hidden" id="y1" name="y1" />
<input type="hidden" id="x2" name="x2" />
<input type="hidden" id="y2" name="y2" />
<h2>Step1: Please select image file</h2>
<div>
<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" />
</div>
<div class="error"></div>
<div class="step2">
<h2>Step2: Please select a crop region</h2>
<img id="preview" />
<div class="info">
<label>File size</label>
<input type="text" id="filesize" name="filesize" />
<label>Type</label>
<input type="text" id="filetype" name="filetype" />
<label>Image dimension</label>
<input type="text" id="filedim" name="filedim" />
<label>W</label> <input type="text" id="w" name="w" />
<label>H</label> <input type="text" id="h" name="h" />
</div>
<input type="submit" value="Upload" />
</div>
</form>
</div>
</div>
</body>
</html>
upload.php
<?php
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// $iWidth = $iHeight = 200; // desired image result dimensions
$iWidth=abs($_POST['x2']-$_POST['x1']);
$iHeight=abs($_POST['y2']-$_POST['y1']);
$iJpgQuality = 90;
if ($_FILES) {
// if no errors and size less than 250kb
if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 250 * 1024) {
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
// new unique filename
$sTempFileName = 'cache/' . md5(time().rand());
// mkdir("cache",0664,true);
chmod('cache', 0664);
//echo $url = $_SERVER['SERVER_NAME'] . dirname(__FILE__);
//echo '<br>';
$root=$_SERVER['DOCUMENT_ROOT'];
$newsTempFileName = $root.'/beta/nikhil/demo/jquery-images-direct-crop/'.$sTempFileName;
// move uploaded file into cache folder
move_uploaded_file($_FILES['image_file']['tmp_name'], $newsTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
return $sResultFileName;
}
}
}
}
}
}
$sImage = uploadImageFile();
echo '<img src="'.$sImage.'" />';
?>
Live Demo : https://www.script-tutorials.com/demos/316/index.html
add jquery and css
I am trying to create a thumb image from an uploaded image and i want to make the thumbnail background color as white...When image uploaded the bg is black...how can i make it white?
HERE IS THE HTML
<!DOCTYPE HTML>
<html>
<head>
<title>PHP upload test</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="">
Select file:<input type="file" name="image" id="image" >
<p>
<input type="submit" value="Upload" name="submit">
</p>
</form>
</body>
</html>
Here is the php code:
<?php
$destination="C:/wamp/www/upload-images/images/";
$thumb_recipient ="C:/wamp/www/upload-images/images/thumbs/";
$thumb_size = 100;
$acceptedMIME= array('image/jpeg', 'image/pjpeg');
if (isset($_POST['submit'])) {
if (is_dir($destination) || is_writable($destination)) { // Check the recipient folder exist
$image = $_FILES['image']['tmp_name'];
$img_name = $_FILES['image']['name'];
$img_type = $_FILES['image']['type'];
if (is_file($image) && is_readable($image)) {
$details = getimagesize($image);
if (is_array($details)) {
$imgOriginalWidth = $details[0];
$imgOriginalHeigth = $details[1];
if ($imgOriginalWidth <= $thumb_size && $imgOriginalHeigth <= $thumb_size) {
$ratio =1;
}
elseif ($imgOriginalWidth > $imgOriginalHeigth) {
$ratio = $thumb_size / $imgOriginalWidth;
}
else
{
$ratio = $thumb_size / $imgOriginalHeigth;
}
$thumbHeigth = round($imgOriginalWidth * $ratio);
$thumbWidth = round($imgOriginalHeigth * $ratio);
$imageName = preg_replace($extensions, '', $img_name);
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
$thumb = imagecreatetruecolor($thumbWidth, $thumbWidth);
if ($ext == 'jpg') {
$resource = imagecreatefromjpeg($image);
imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $thumbWidth, $thumbHeigth, $imgOriginalWidth, $imgOriginalHeigth);
$imgthumbname = $imageName.'.jpeg';
$success = imagejpeg($thumb, $thumb_recipient . $imgthumbname, 100);
if ($success) {
echo "Successful";
}
imagedestroy($thumb);
}
}
else
{
echo "File is invalid..it is not an array";
}
}
else{
echo "Uploaded file cannot be open";
}
}
else
{
echo "The directory folder is not valid";
}
}
?>
You can use http://php.net/manual/en/function.imagefill.php starting at any point of background - probably 0,0 should be good. (If function is not found check if you have GD extension turned on.)
I am using jcrop to crop images.
This is the form that i upload the image and crop.
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">
<!-- hidden crop params -->
<input type="hidden" id="x1" name="x1" />
<input type="hidden" id="y1" name="y1" />
<input type="hidden" id="x2" name="x2" />
<input type="hidden" id="y2" name="y2" />
<div><input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" /></div>
<div class="error"></div>
<div class="step2">
<h2>Step2: Please select a crop region</h2>
<img id="preview" />
<div class="info">
<label>File size</label> <input type="text" id="filesize" name="filesize" />
<label>Type</label> <input type="text" id="filetype" name="filetype" />
<label>Image dimension</label> <input type="text" id="filedim" name="filedim" />
<label>W</label> <input type="text" id="w" name="w" />
<label>H</label> <input type="text" id="h" name="h" />
</div>
<input type="submit" value="Upload" />
</div>
</form>
upload.php file which upload cropped image to avatar directory.
<?php function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$iWidth = $iHeight = 200; // desired image result dimensions
$iJpgQuality = 90;
if ($_FILES) {
// if no errors and size less than 250kb
if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 250 * 1024) {
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
// new unique filename
$sTempFileName = 'avatar/' . md5(time().rand());
// move uploaded file into cache folder
move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
/*case IMAGETYPE_GIF:
$sExt = '.gif';
// create a new image from file
$vImg = #imagecreatefromgif($sTempFileName);
break;*/
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
return $sResultFileName;
}
}
}
}
}
}
$sImage = uploadImageFile();
echo '<img src="'.$sImage.'" />';
?>
My Question:
Right now it just upload the cropped image in avatar directory with width and height of 200px.
I want to also upload that cropped image in to two other directories
avatar1 with width and height of 500px
avatar2 with width and height of 700px
Any help will be appreciated.
Add arguments to your function, e.g. uploadImageFile($dirName, $iWidth, $iHeight) and then invoke it multiple times with different sizes
<?php
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$iJpgQuality = 90;
if ($_FILES) {
// if no errors and size less than 250kb
if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 250 * 1024) {
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
if (!is_dir('avatar')) {
mkdir('avatar');
}
// new unique filename
$sTempFileName = 'avatar/' . md5(time().rand());
// move uploaded file into cache folder
move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
$sResultFileName = copyImageFile('avatar', $sTempFileName, 200, 200, $iJpgQuality);
if ($sResultFileName) {
copyImageFile('avatar1', $sTempFileName, 500, 500);
copyImageFile('avatar2', $sTempFileName, 700, 700);
#unlink($sTempFileName);
return $sResultFileName;
}
}
}
}
}
return false;
}
function copyImageFile($dirName, $originImageName, $iWidth, $iHeight, $iJpgQuality = 90) {
if (file_exists($originImageName) && filesize($originImageName) > 0) {
$aSize = getimagesize($originImageName); // try to obtain image info
if (!$aSize) {
#unlink($originImageName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
$vImg = #imagecreatefromjpeg($originImageName);
break;
/*case IMAGETYPE_GIF:
$sExt = '.gif';
// create a new image from file
$vImg = #imagecreatefromgif($sTempFileName);
break;*/
case IMAGETYPE_PNG:
$sExt = '.png';
$vImg = #imagecreatefrompng($originImageName);
break;
default:
#unlink($originImageName);
return;
}
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);
// define a result image filename
if (!is_dir($dirName)) {
mkdir($dirName);
}
$newImageName = $dirName . DIRECTORY_SEPARATOR . md5(time().rand()) . $sExt;
// output image to file
imagejpeg($vDstImg, $newImageName, $iJpgQuality);
//#unlink($sTempFileName);
return $newImageName;
}
return false;
}
$sImage = uploadImageFile();
echo '<img src="'.$sImage.'" />';
?>
I have a post method in my php page that is called once the page is created. Now I have a form on this same page and when you click it it should "refresh" the page with an image that is cropped. I get weird text on my screen when I run this:
First post method:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($_FILES['afbeelding']['error'] == 0) {
$imageinfo = getimagesize($_FILES['afbeelding']['tmp_name']);
if(filesize($_FILES['afbeelding']['tmp_name']) > 204800) {?> <script type="text/javascript"> alert("Maximale bestandsgrootte: 200KB"); window.location = "/inside.php"</script> <?php }
else{
move_uploaded_file($_FILES['afbeelding']['tmp_name'], 'images/' . $_FILES['afbeelding']['name']);}
The form:
<form method="post" action="?action=showCrop">
<input type="hidden" name="x" value="" />
<input type="hidden" name="y" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" />
<input type="hidden" name="image" value="images/<?php echo $_FILES['afbeelding']['name']; ?>" />
<input type="submit" value="Verklein afbeelding!" name="submit"/>
</form>
<?php
echo '<img src="getimage.php?file=images/' . $_FILES['afbeelding']['name'] . '">';
And the method that should be called after submitting the form:
function showCrop(){
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
$jpeg_quality = 90;
$src = $_POST['image'];
$ext = end(explode(".", $_POST['image']));
switch($ext)
{
case 'jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
//header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
exit;
break;
case 'png';
$img_r = imagecreatefrompng($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
//header('Content-type: image/png');
imagepng($dst_r,null,8);
exit;
break;
}
}