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>
Related
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>
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...
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.)
<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?
I'm trying to make a site in which I can upload a file to my sql database, but it does not seem to work.
This is my code;
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="Image">
<input type="submit" value="Upload">
</form>
<?php
//Connecting to the database
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("picturedatabase") or die(mysql_error());
$file = $_FILES['Image']['tmp_name'];
if(!isset($file))
{
echo "Select an image";
}
else
{
$image = addslashes(file_get_contents($_FILES['Image']['tmp_name']));
$image_name = addslashes($FILES['Image']['name']);
$image_size = getimagesize($FILES['Image']['tmp_name']);
}
if($image_size==FALSE)
{
echo "That's not an image.";
}
else
{
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')"))
{
echo "There was a problem uploading the image";
}
else
{
$lastid = mysql_insert_id();
echo "Image uploaded!<p />Your image:<p /> <img src=show.php?id=$lastid>";
}
}
?>
</body>
</html>
And when I run the file, the form stuff shows up (the buttons and I can also select a file), but it also says
"Notice: Undefined index: Image in C:\ProgramFiles\Xampp\htdocs\Database\upload.php on line 16
Notice: Undefined variable: image_size in C:\ProgramFiles\Xampp\htdocs\Database\upload.php on line 29"
Could someone tell me what I did wrong and help me fix this?
You should save the files in some folder during the upload process and save the name of file in database, so later you can call the name of file from database and link it as a hyperlink to download, i am using the following code to upload images in a folder called files and saving the name of files in database. At the end i have the file name in variable $newname
if ($_FILES['file']['name']) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
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/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 500000)
&& in_array($extension, $allowedExts)
) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$ext = end(explode(".", $_FILES["file"]["name"]));
$filename = current(explode(".", $_FILES["file"]["name"]));
$newname = $filename . '_' . time() . '.' . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],
"files/" . $newname);
}
} else {
echo "<div class='alert alert-success'>Image type or size is not valid.</div>";
}
}
I hope this helps you:
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<?php
function output_errors($error) {
echo '<ul><li><font color="red">'.$error.'</font>/li></ul>';
}
if($_POST) {
//Connecting to the database
$connect = mysqli_connect("localhost", "root" ,"", "picturedatabase");
$name = $_FILES['Image']['name'];
if(!empty($name)) {
$tmp = $_FILES['Image']['tmp_name'];
$type = $_FILES['Image']['type'];
$allowed_type = array('image/jpg', 'image/jpeg', 'image/gif', 'image/png');
if(!in_array($type, $allowed_type)) {
$error[] = $type. ' is not allowed file type';
}
} else {
$error[] = 'There are empty fields';
}
if(!empty($error)) {
echo output_errors($error);
} else if(empty($error)){
$path = 'images/'.$name;
$query = mysqli_query($connect, "INSERT INTO `images` (`image`) VALUES ('$path')");
if(!$query) {
echo 'Insert into db went wrong';
} else {
move_uploaded_file($tmp, $path);
echo '<font color="green">Upload succesful</font>';
}
}
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="Image">
<input type="submit" value="Upload">
</form>
</body>
</html>