Converting multiple photos by size in php - php

Here is my code of importing and converting a photo into database and in a path on server drive.
I want to upload multiple photos in database and convert all of them in a smaller size. For example when I press button "chose file" I want to select more than one photo , and submit all of them. After they need to go in my database, and to convert into a smaller size (all of them, not only one).
<?php include("config.php") ?>
<?php
$name = '';
$type = '';
$size = '';
$error = '';
function compress_portrait($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
} if ($_POST) {
if ($_FILES["portrait"]["error"] > 0) {
$error = $_FILES["portrait"]["error"];
}
else if (($_FILES["portrait"]["type"] == "image/gif") ||
($_FILES["portrait"]["type"] == "image/jpeg") ||
($_FILES["portrait"]["type"] == "image/png") ||
($_FILES["portrait"]["type"] == "image/pjpeg")) {
$fname=$_FILES['portrait']['name'];
$url = ('upload/portrait/'.$fname );
$filename = compress_portrait($_FILES["portrait"]["tmp_name"], $url, 50);
$query="INSERT into gallery (`USER_CODE`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`, `CATEGORY`) VALUES('$user_id','$fname','$file_size','$file_type' , 'portrait'); ";
mysqli_query($con , $query);
}}else {
$error = "Uploaded image should be jpg or gif or png";
}
?>
<div class="container align-center" >
<h1 class="mt-3">Add Images on Gallery</h1>
<h4 style="margin-top: 12px; ">Portrait:</h4>
<form action="" method="POST" id="img_compress" enctype="multipart/form-data">
<input type="file" name="portrait" id="portrait" multiple/>
<input type="submit" name="submit" id="submit" class="submit btn-primary"/>
</form>
</div>

Related

Need help on Uploading Multiple Image with compression

I have these code below to upload single image with compression. but right now I want to upload multiple image. Can someone help with with upload multiple image using the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Compress and Check</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" accept="image/*" />
<input type="submit" name="btnsubmit" value="submin" id="submit" />
</form>
</body>
</html>
<?php
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
elseif ($info['mime'] == 'image/jpg') $image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
if(isset($_POST['btnsubmit'])){
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != ""){
$filename = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_error = $_FILES['file']['error'];
$target_dir = "img/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$uploadOk = 1;
if(file_exists($target_file)){ exist or not
echo "<script>alert('sorry, file already exists.');</script>";
$uploadOk = 0;
}else if ($file_size > 500000) {
echo "<script>alert('sorry, your file is too large.');</script>";
$uploadOk = 0;
}else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "<script>alert('sorry, only JPG, JPEG, PNG & GIF files are allowed.');</script>";
$uploadOk = 0;
}else if($file_error > 0){
echo "<script>alert('Your file is corrupted!');</script>";
$uploadOk = 0;
}
if($uploadOk == 0){
echo "<script>alert('sorry, your file was not uploaded!');</script>";
}else{
$rand = md5(sha1(rand(10000, 10000000)));
$url = $target_dir . $rand . '.jpg';
$filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
}
}else{
echo "<script>alert('No image to upload!');</script>";
}
}
?>
Thank you in advance.....
Change a bit for the input "file" element:
<input type="file" multiple name="file[]" id="file" accept="image/*" />
Its ok, now you can use $_FILES["file"]["name"][0] to get the name of 1st file, or _FILES["file"]["tmp_name"][1] to get the tmp_name of 2nd file, and so on.
I hope you understand, i cannot explain more because i am using phone...

How can i create white background color to an uploaded thumb image in php?

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.)

PHP reduce file size on image

<html>
<head>
</head>
<body>
<form action="tutorial.php" method="post" enctype="multipart/form-data">
<b><u>UPLOAD FILE</u></b><br />
Attachment : <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Upload" /><br />
<hr />
</body>
<?php
function compress_image($source, $destination, $quality)
{
$info = getimagesize($source);
if($info['mime'] == 'image/jpeg' || $info['mime'] == "image/jpg")
{
$image = imagecreatefromjpeg($source);
}
else if($info['mime'] == 'image/gif')
{
$image = imagecreatefromgif($source);
}
else if($info['mime'] == 'image/png')
{
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
if(isset($_POST['submit']) && $_POST['submit'] == 'Upload')
{
$type = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
if(($type == "image/jpg") || ($type == "image/jpeg") || ($type == "image/gif") || ($type == "image/png"))
{
$source = $tmp_name;
$destination = "destination.jpg";
echo 'File size (before): '.$size.'<br />';
$filename = compress_image($source, $destination, 75);
echo 'File size (after): '.filesize($destination).'<br />';
}
else
{
echo "Invalid file size. Only jpg, jpeg, gif, png allowed.";
}
}
?>
From above code, I get the following output after I upload jpeg file:
Original file size: 7034
Compress file size: 7092
I really don't know why after I compress, it is increased? If I upload a large file size, the file size will reduce. When I upload a small file size, the file size is an increase. How should I do?

Reduce Image size in php while uploading

PHP - I am using this code to upload image file but i don't how to reduce the image file size but quality should be maintain .
$todir = 'members/'.$_SESSION[' valid_user '].'/';
$RandomNum = rand(0, 9999999999);
$info = explode('.', strtolower( $_FILES['Image']['name']) ); // whats the extension of the file
if(move_uploaded_file( $_FILES['Image']['tmp_name'], $todir . basename($_FILES['Image']['name']-$RandomNum) ) )
{
$handle= 'members/'.$_SESSION[' valid_user '].'/'.basename($_FILES['Image']['name']-$RandomNum);
echo 'uploaded';
}
Have you tried using ImageMagick to bring your images down to more appropriate sizes? (http://php.net/manual/en/imagick.setimagecompressionquality.php)
$name = "";
$type = "";
$size = "";
$error = "";
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
if ($_POST) {
if ($_FILES["file"]["error"] > 0){
$error = $_FILES["file"]["error"];
} else if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")){
$url = $_FILES["file"]["name"];
$filename = compress_image($_FILES["file"]["tmp_name"], $url, 30);
$buffer = file_get_contents($url);
}else {
$error = "Uploaded image should be jpg or gif or png";
}
}
<html>
<head>
<title>Php code compress the image</title>
</head>
<body>
<div class="message">
<?php if($_POST){ if ($error) { ?>
<label class="error"><?php echo $error; ?></label>
<?php } } ?>
</div>
<legend>Upload Image:</legend>
<form action="" name="myform" id="myform" method="post" enctype="multipart/form-data">
<label>Upload:</label>
<input type="file" name="file" id="file"/>
<input type="submit" name="submit" id="submit" class="submit btn-success"/>
</form>
</body>
</html>

uploading file through iframe doesn't work in IE

I have two files iframe.php, iframe.html. iframe.php contains a file's uploading form which i want to display in iframe.html as an iframe (only for IE < 10 otherwise i can upload using ajax without any problems).
it's working fine in IE.10, but in IE.9 i need to click twice on the submit button to upload, where in IE.8 it doesn't work at all and the $output always return Error: invalid file and also need to be clicked twice, i'm not sure what the problem is! any help would be great.
iframe.php
<div id="uploadImage">
<form method='POST' enctype='multipart/form-data' action='<?php echo $_SERVER['PHP_SELF'] ?>'>
<input type="text" disabled placeholder="Choose an Image to upload" id="file_input" name="file_input" />
<input type="button" id="file_btn" value="" onClick="document.getElementById('file').click()" />
<input type="submit" id="upload" value="" />
<div style="width: 0; height: 0; overflow: hidden;">
<input type="file" id="file" name="file" />
</div>
</form>
<div id="properties" class="texxt">
<p>Name: <br/>
Size: max 2 MB or 2000 KB<br/>
Type: (jpg, jpeg, png, gif)
</p>
</div>
<div id="results">
<?php
$status = "Close";
$source = "";
if( isset($_FILES['file']))
{
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
$size = (int) $_SERVER['CONTENT_LENGTH'];
if ( (($_FILES["file"]["type"] == "image/gif") ||
($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/jpg") ||
($_FILES["file"]["type"] == "image/png")) &&
in_array($extension, $allowedExts) &&
($size < (2 * 1024 * 1024)) )
{
if ($_FILES["file"]["error"] > 0)
{
$output = "Return Code: " . $_FILES["file"]["error"];
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
$output = "Error: File already exists. Please rename your file or chose a different one";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
$status = "Add Image";
$output = "Uploaded Successfully";
$source = sprintf(" !img! %s !*img! ", $_FILES["file"]["name"]);
}
}
}
else
{
if (!in_array($extension, $allowedExts))
{
$output = "Error: Please select an image.";
}
elseif ( ($size > (2 * 1024 * 1024)) && in_array($extension, $allowedExts) )
{
$output = "Error: File size(" . $size . ") exceeds the limit of 2 mb.";
}
else
{
$output = "Error: Invalid file";
}
}
echo $output;
}
?>
</div>
<p align="center">
<input type="hidden" name="source" id="source" class="source" value="<?php echo $source ?>" />
<input type="button" id="close" class="close" value="<?php echo $status ?>" />
</p>
</div>
<script>
document.getElementById('file').onchange = function(){
var path = this.value.replace(/C:\\fakepath\\/, ''),
props = document.getElementById('properties');
props.innerHTML = props.innerHTML.replace('Name: ', 'Name: ' + path);
document.getElementById('file_input').value = path;
document.getElementById('results').innerHTML = "";
};
</script>
iframe.html
<div id="iframe" style="height: 296px; width: 481px">
</div>
<script>
var iframe = document.createElement('iframe');
iframe.src = "iframe.php";
iframe.frameBorder = "no";
iframe.allowTransparency = "true";
document.getElementById('iframe').appendChild(iframe);
</script>
IE doesn't allow manipulation of the type="file" input element from javascript due to security reasons. Setting the filename or invoking a click event to show the browser dialog will result in an "Access is denied" error on the form submit, user has to click on the file input manually.
as for the invalid file error in IE.8, the proplem is with the $_FILES['file']['type'], i had this problem myself before. when using var_dump($_FILES['file']['type']) you can see that it shows file types as following:
jpeg -> pjpeg
jpg -> pjpeg
png -> x-png
gif -> gif
to fix the problem add x-png and pjpeg to the allowed file types:
if ( (($_FILES["file"]["type"] == "image/gif") ||
($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/jpg") ||
($_FILES["file"]["type"] == "image/pjpeg") ||
($_FILES["file"]["type"] == "image/png") ||
($_FILES["file"]["type"] == "image/x-png")) &&
in_array($extension, $allowedExts) &&
($size < (2 * 1024 * 1024)) )
{

Categories