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
Related
I'm working on uploading an image file from a form to a folder on the server and recording the location in a mysql db via PHP and I'm having a lot of trouble with it. Currently this is my html code for the form:
<body>
<div class="container">
<form action="upload.php" method="post" class="m-auto" style="max-width:600px">
<h3 class="my-4"><?php echo "{$family_info['Family_Name']} Family Image Upload";?></h3>
<hr class="my-4" />
<div class="form-group mb-3 row"><label for="family_mem5" class="col-md-5 col-form-label">Family Member</label>
<div class="col-md-7"><select class="form-select custom-select custom-select-lg" name= "family_mem" id="family_mem5">
<option></option>
<?php
while($row = $family_members-> fetch_array(MYSQLI_BOTH))
{
echo "<option value='".$row['Family_Member']."'>".$row['Family_Member']."</option>";
}
?>
</select><small class="form-text text-muted">Please select a family member to upload a photo for.</small></div>
</div>
<hr class="bg-transparent border-0 py-1" />
<div class="form-group mb-3 row">
<label for="image1" class="col-md-5 col-form-label">Image</label>
<div class="col-md-7"><input type="file" class="form-control form-control-lg" id="image1" name="image" required><small class="form-text text-muted">Please select an image.</small></div>
</div>
<hr class="my-4" />
<div class="form-group mb-3 row"><label for="upload-image8" class="col-md-5 col-form-label"></label>
<div class="col-md-7"><button class="btn btn-primary btn-lg" type="submit" name="submit" id="submit">Upload Image</button></div>
</div>
</form>
</div>
This is my PHP code for the upload.php file that the form POSTs to.
<?php
session_start();
$membernumber = $_SESSION['membernumber'];
$family_member = $_POST['family_mem'];
echo "Member Number: ".$membernumber;
echo "<br />";
echo "Family Member: ".$family_member;
echo "<br />";
/*
* Custom function to compress image size and
* upload to the server using PHP
*/
function compressImage($source, $destination, $quality) {
// Get image info
$imgInfo = getimagesize($source);
$mime = $imgInfo['mime'];
// Create a new image from file
switch($mime){
case 'image/jpeg':
$image = imagecreatefromjpeg($source);
break;
case 'image/png':
$image = imagecreatefrompng($source);
break;
case 'image/gif':
$image = imagecreatefromgif($source);
break;
default:
$image = imagecreatefromjpeg($source);
}
// Save image
imagejpeg($image, $destination, $quality);
// Return compressed image
return $destination;
}
// File upload path
$uploadPath = "uploads/";
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
echo "empty";
}
// If file upload form is submitted
$status = $statusMsg = 'Image uploaded for so and so';
if(isset($_POST["submit"]))
{
$status = 'error';
if(!empty($_FILES["image"]["name"]))
{
// File info
$file = $_FILES['image']['name'];
$ext = pathinfo($file, PATHINFO_EXTENSION);
$fileName = "$family_member.$ext";
echo 'Filename: '.$fileName;
$imageUploadPath = $uploadPath . $fileName;
$fileType = pathinfo($imageUploadPath, PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('jpg','JPG','png','jpeg','gif');
if(in_array($fileType, $allowTypes))
{
// Image temp source
$imageTemp = $_FILES["image"]["tmp_name"];
$imageSize = $_FILES["image"]["size"];
// Compress size and upload image
$compressedImage = compressImage($imageTemp, $imageUploadPath, 75);
if($compressedImage)
{
$compressedImageSize = filesize($compressedImage);
$status = 'success';
// $statusMsg = "Image compressed successfully.";
}
else
{
$statusMsg = "Image compress failed!";
}
}
else
{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
}
}
else
{
$statusMsg = 'Please select an image file to upload.';
}
}
// Display status message
echo $statusMsg;
?>
The issue is that the image file is showing up empty as you can see from the check empty code, as if it never makes it over. What could I be doing wrong? I've gotten the upload working in smaller example code before but as soon as I start adding features it falls apart. Right now I'm lost as to why it does not pass the file from the form.
Thank you very much for any help. I'm surprised by how hard moving files is in PHP, or maybe how clueless I am lol.
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 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>