PHP reduce file size on image - php

<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?

Related

Converting multiple photos by size in 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>

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

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>

Unable to find a way to resize an image using PHP

I want to resize any image uploaded to 200*200 pixels.I have been looking over scripts all over the net,have found many but unable to use any.I don't want any other controls just resizing it to specific size.
<!-<?php session_start();?>
<?php session_start();?>
<?php $u_name=birju;?>
<?php require_once("mydb.php");?>
<?php
define ("MAX_SIZE","100");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if(isset($_POST['Submit']))
{
$image=$_FILES['image']['name'];
if ($image)
{
$filename = stripslashes($_FILES['image']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
$size=filesize($_FILES['image']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
$image_name = $u_name.'.'.$extension;
$newname="images/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}
$me=mysql_query("insert into img_upload values(\"\",\"$u_name\",\"$newname\")");
if(!$me)
{
die("database query failed".mysql_error());
}
?>
<!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image"></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>
-->
Using PHP GD, instead of your code about copying the image from tmp_name to new_name use:
$image = file_get_contents($_FILES['image']['tmp_name']);
$new_image = imagecreatetruecolor(200, 200);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, 200, 200, imagesx($image), imagesy($image));
file_put_contents($newname, $new_image);
Check out timthumb: http://code.google.com/p/timthumb/

Categories