How to show cropped image on same page - php

I want to be able to crop a file three time (so you have a big, medium and small image). The problem right now is that the JCrop is working. Uploading the file works, and you can actually "crop" the file. The problem is that the cropped file is not shown when pressed on the submit button.
As you can see in the code I use a function ShowCrop to keep things tidy, the function is called before the submit form begins. When I run the page I see nothing (no form, no image). Something obviously goes wrong that this function.
I am a beginning PHP scripter, and I am sure there are a lot of faults in this script. Please remind me of those so I can learn!
Here's the code:
<?php
//Original upload
if(isset($_POST['upload'])) {
$name = '_original';
$path_info = pathinfo($_FILES['afbeelding']['name']);
$file_extension = $path_info["extension"];
$newname = $path_info['filename'].$name.".".$file_extension;
move_uploaded_file($_FILES['afbeelding']['tmp_name'], 'images/' . $newname);}
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<?php echo $newname ?>
Big format:
<form method="post" action="upload.php">
<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="fextension" value="<?php echo $file_extension ?>" />
<input type="hidden" name="name" value=<?php echo $newname ?> />
<input type="hidden" name="image" value="images/<?php echo $_FILES['afbeelding'][$newname]; ?>" />
<input type="submit" value="Crop image!" />
</form>
<?php
echo '<img src="getimage.php?file=images/' . $newname . '">';
}
phpinfo();
}
else if(isset($_POST['x'])) //GROOT -> MIDDEL
{
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<?php
echo $_POST['name'];
showCrop($_POST['fextension']);
//echo '<img src="getimage.php?file=images/' . $_POST['name'] . '">';
?> Middel formaat:
<form method="post" action="upload.php">
<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'][$newname]; ?>" />
<input type="submit" value="Crop image!" />
</form><?php
}
function showCrop($ext){
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
$jpeg_quality = 90;
$src = $_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);
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']);
move_uploaded_file($dst_r, 'images/' ."test". $newname);
break;
exit;
}
}
?>

I've rewritten the logic of the code so it'll automatically reload the page until each size/crop has been completed.
This isn't pretty code and is lacking a lot of additional functions (database, security, etc), but it demonstrates how you can achieve what you need (hopefully).
<?php
// Resize image and return filename
function saveCrop($source, $destination) {
// Get extension
$ext = strtolower(pathinfo($source, PATHINFO_EXTENSION));
// Resize/Crop image
switch($ext)
{
case 'jpg';
$img_r = imagecreatefromjpeg($source);
$dst_r = ImageCreateTrueColor($_POST['w'], $_POST['h']);
imagecopyresampled($dst_r,$img_r, 0, 0, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
imagejpeg($dst_r, $destination);
return true;
break;
case 'png';
$img_r = imagecreatefrompng($source);
$dst_r = ImageCreateTrueColor($_POST['w'], $_POST['h']);
imagecopyresampled($dst_r,$img_r, 0, 0, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
imagepng($dst_r, $destination);
return true;
break;
default:
die('Invalid file extension: ' . $ext);
}
}
// Save uploaded file to web server for future processing
if ( isset($_FILES['uploaded-file']))
{
// Check for valid file type
$ext = strtolower(pathinfo($_FILES['uploaded-file']['name'], PATHINFO_EXTENSION));
if ( ! in_array($ext, array('jpg', 'png')))
{
die('Unsupported file type');
}
$source_file = 'images/original-' . $_FILES['uploaded-file']['name'];
if ( ! move_uploaded_file($_FILES['uploaded-file']['tmp_name'], $source_file))
{
die('Unable to move uploaded file (possibly due to write permissions)');
}
// Set target file
$target_file = 'images/large-' . $_FILES['uploaded-file']['name'];
}
// Process crop/resize requests
elseif (isset($_POST['x']))
{
$source_file = $_POST['source'];
$target_file = $_POST['target'];
saveCrop($source_file, $target_file);
// No more cropping is required after the small image
if (substr($target_file, 0, 12) == 'images/small')
{
header('Location: completed.php');
}
else
{
// Determine new source file
$source_file = $target_file;
// Determine new target file
$target_file = str_replace(
array('images/medium', 'images/large', 'images/original'),
array('images/small', 'images/medium', 'images/large'),
$target_file
);
}
}
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<form method="post" action="">
<input type="text" name="x" value="" />
<input type="text" name="y" value="" />
<input type="text" name="w" value="" />
<input type="text" name="h" value="" />
<input type="text" name="source" value="<?php echo $source_file; ?>" />
<input type="text" name="target" value="<?php echo $target_file; ?>" />
<input type="submit" value="Crop" />
</form>
<img src="<?php echo $source_file; ?>" id="img">

Related

my cropped image is just a black colored box of 2KB?

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

How to load image which of last upload?

I am loading a image which is jpg but what if the user uploads a png file or jpeg file as profile image where he already had a file in jpg.
SAME NAME example : abc#mail.com_profileimage.ext
I am getting this image by direct link through url.
<img style="width: 100%" src="http://proconstruct.co.in/upload_images/<?php echo $email.'_profileimage.jpg';?>" onerror="this.src = 'http://proconstruct.co.in/images/noimage.jpg'; ">
If i use $images = glob($dirname . "*"); with the give prefix above how can i get last saved image
UPLOAD and CROP CODE
<?php
error_reporting (E_ALL ^ E_NOTICE);
$upload_path = "upload_images/";
$thumb_width = "150";
$thumb_height = "150";
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$thumb_image_name);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumb_image_name,100);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumb_image_name);
break;
}
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}
if (isset($_POST["upload_thumbnail"])) {
$filenam = $_POST['filename'];
$filenam = pathinfo($filenam);
$extn = $filenam['extension'];
$large_image_location = $upload_path.$_POST['filename'];
$thumb_image_location = $upload_path."thumb_".$_POST['filename'];
$myemail = $this->session->userdata('email');
$thumb_image_location = $upload_path.$myemail."_profileimage.".$extn;
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload File and Crop</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/cropimage.css" />
<link type="text/css" href="css/imgareaselect-default.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/jquery.imgareaselect.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$('#submitbtn').click(function() {
$("#viewimage").html('');
$("#viewimage").html('<img src="images/loading.gif" />');
$(".uploadform").ajaxForm({
url: 'upload_sup',
success: showResponse
}).submit();
});
});
function showResponse(responseText, statusText, xhr, $form){
if(responseText.indexOf('.')>0){
$('#thumbviewimage').html('<img src="<?php echo $upload_path; ?>'+responseText+'" style="position: relative;" alt="Thumbnail Preview" />');
$('#viewimage').html('<img class="preview" alt="" src="<?php echo $upload_path; ?>'+responseText+'" id="thumbnail" />');
$('#filename').val(responseText);
$('#thumbnail').imgAreaSelect({ aspectRatio: '1:1', handles: true , onSelectChange: preview });
}else{
$('#thumbviewimage').html(responseText);
$('#viewimage').html(responseText);
}
}
</script>
<script type="text/javascript">
function preview(img, selection) {
var scaleX = <?php echo $thumb_width;?> / selection.width;
var scaleY = <?php echo $thumb_height;?> / selection.height;
$('#thumbviewimage > img').css({
width: Math.round(scaleX * img.width) + 'px',
height: Math.round(scaleY * img.height) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
var x1 = Math.round((img.naturalWidth/img.width)*selection.x1);
var y1 = Math.round((img.naturalHeight/img.height)*selection.y1);
var x2 = Math.round(x1+selection.width);
var y2 = Math.round(y1+selection.height);
$('#x1').val(x1);
$('#y1').val(y1);
$('#x2').val(x2);
$('#y2').val(y2);
$('#w').val(Math.round((img.naturalWidth/img.width)*selection.width));
$('#h').val(Math.round((img.naturalHeight/img.height)*selection.height));
}
$(document).ready(function () {
$('#save_thumb').click(function() {
var x1 = $('#x1').val();
var y1 = $('#y1').val();
var x2 = $('#x2').val();
var y2 = $('#y2').val();
var w = $('#w').val();
var h = $('#h').val();
if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
alert("Please Make a Selection First");
return false;
}else{
return true;
}
});
});
</script>
</head>
<body style="background-color: #6db4e7">
<!-- content -->
<section>
<div class="container">
<div class="crop_box">
<form class="uploadform" method="post" enctype="multipart/form-data" action='upload.php' name="photo">
<div class="crop_set_upload">
<div class="crop_upload_label">Upload files: </div>
<div class="crop_select_image"><div class="file_browser"><input type="file" name="imagefile" id="imagefile" class="hide_broswe" /></div></div>
<div class="crop_select_image"><input type="submit" value="Upload" class="upload_button" name="submitbtn" id="submitbtn" /></div>
</div>
</form>
<div class="crop_set_preview">
<div class="crop_preview_left">
<div class="crop_preview_box_big" id='viewimage'>
</div>
</div>
<div class="crop_preview_right">
Preview Image
<div class="crop_preview_box_small" id='thumbviewimage' style="position:relative; overflow:hidden;"> </div>
<form name="thumbnail" action="profileimage" method="post">
<input type="hidden" name="x1" value="" id="x1" />
<input type="hidden" name="y1" value="" id="y1" />
<input type="hidden" name="x2" value="" id="x2" />
<input type="hidden" name="y2" value="" id="y2" />
<input type="hidden" name="w" value="" id="w" />
<input type="hidden" name="h" value="" id="h" />
<input type="hidden" name="wr" value="" id="wr" />
<input type="hidden" name="filename" value="" id="filename" />
<div class="crop_preview_submit"><input type="submit" name="upload_thumbnail" value="Save Thumbnail" id="save_thumb" class="submit_button" /> </div>
</form>
</div>
</div>
</div>
</div>
</section>
</body>
</html>

Post form method with already existing post in page

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;
}
}

jcrop is saving image which is just black background

I am using jcrop to crop and save image but what i get is black image , what is the problem in below code:
Second :: also it navigate to some other page , i dont want navigation . how to do that ?
<?php
/**
* Jcrop image cropping plugin for jQuery
* Example cropping script
* #copyright 2008-2009 Kelly Hallman
* More info: http://deepliquid.com/content/Jcrop_Implementation_Theory.html
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/pool.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']);
imagejpeg($dst_r,'null.jpg',$jpeg_quality);
exit;
}
// If not a POST request, display page below:
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<script language="Javascript">
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
onSelect: updateCoords
});
});
function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
function checkCoords()
{
if (parseInt($('#w').val())) return true;
alert('Please select a crop region then press submit.');
return false;
};
</script>
</head>
<body>
<!-- This is the image we're attaching Jcrop to -->
<img src="demo_files/pool.jpg" id="cropbox" />
<!-- This is the form that our event handler fills -->
<form action="crop.php" method="post" onsubmit="return checkCoords();">
<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 type="submit" value="Crop Image" />
</form>
</body>
</html>
I solved by changing it to following code,
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/pool.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']);
imagejpeg($dst_r,'hello.jpg',$jpeg_quality);
exit;
}
// If not a POST request, display page below:
?>

Multiple Upload Forms

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>

Categories