Resize image when uploaded - php

What is wrong with my code I need to resize image when upload in variable $new_width and $new_height is dimension for image. I think it's problem in $newname variable because it is working before when I added :D
<meta charset="utf-8" />
<?php
include 'config.php';
mysqli_set_charset($db, 'utf8');
$id = $_COOKIE["id"];
if (isset($_POST["action"])){
$newname = substr(md5(rand() * time()), 5,10);
$folder = "image/";
$folder2 = "image/thumb/";
$filetmp = $_FILES["filep"]["tmp_name"];
$filename = $_FILES["filep"]["name"];
$filetype = $_FILES["filep"]["type"];
$filesize = $_FILES["filep"]["size"];
$fileinfo = getimagesize($_FILES["filep"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "$folder".$newname.$filename;
$filepath_thumb = "$folder".$filename;
if($filetmp == ""){
echo "Upload image";
}
else {
if($filesize > 2097152){
echo "Less then 2 mb";
}
else{
if($filetype != "image/jpeg" && $filetype != "image/png"
&& $filetype != "image/gif" && $filetype != "image/jpg"){
echo ".jpeg, .jpg, .gif, .png";
}
else{
move_uploaded_file($filetmp,$filepath);
if($filetype == "image/jpeg"){
$imagecreate = "imagecreatefromjpeg";
$imageformat = "imagejpeg";
}
if($filetype == "image/png"){
$imagecreate = "imagecreatefrompng";
$imageformat = "imagepng";
}
if($filetype == "image/gif"){
$imagecreate= "imagecreatefromgif";
$imageformat = "imagegif";
}
if($filetype == "image/jpg"){
$imagecreate= "imagecreatefromjpg";
$imageformat = "imagejpg";
}
$new_width = "200";
$new_height = "150";
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = $imagecreate($filepath); //photo folder
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $filewidth, $fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
$res = mysqli_query($db, "UPDATE Imager SET Cover='".$newname.$filename."' WHERE IDImg ='$id'");
if($res) {
echo "Good.";
}
else {
echo "Not Good.";
}
}
}
}
}
header( "Refresh:2; url=img.php", true, 303);
?>

I would suggest you use a library like Imagine - it will make this process much simpler.

Related

Error while creating thumbnail in php for multiple image upload

I use following code to upload, rename, compress, create thumbnail everything works fine, And recently i noticed while creating thumb it creates fresh copy of thumb images for previously uploaded images also(create thumbnail for uploaded and uploading images too)
Problem:
When form is submitted it crates thumb for uploading image and uploaded images(image file that are present in older).
how do i solve this problem
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
if
(move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['tmp_name'][$key], 0);
}
} else {
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key + 1) . ' = $row[0];';
eval($codestr);
} else {
$codestr = '$file' . ($key + 1) . ' = NULL;';
eval($codestr);
}
}
}
$orig_directory = "$desired_dir";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$dir_handle = opendir($orig_directory);
if ($dir_handle > 1) {
$allowed_types = array('jpg', 'jpeg', 'gif', 'png');
$file_type = array();
$ext = '';
$title = '';
$i = 0;
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..') {
continue;
}
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
if (in_array($ext, $allowed_types)) {
$nw = 125;
$nh = 90;
$source = "$desired_dir{$file_name}";
$stype1 = explode(".", $source);
$stype = $stype1[count($stype1) - 1];
$dest = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
compress($source, "$desired_dir/" . $file_name, 50);
}
}closedir($dir_handle);
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file1, PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file2, PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file3, PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file4, PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: /post/price_plan.php');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
} else if ($targetRatio > $srcRatio) {
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
} else {
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
Bounty Edit
if there is any good and faster function to do please.
all i need is to upload, rename, compress, create thumbnail and save name to DB
The code is need much more optimization. you are iterating the file folder again every time instead of looping the just uploaded files.
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$file = [];
$nw = 125;
$nh = 90;
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
$file_name_with_ext = $file_name . $sExt;
$source = = $desired_dir . $file_name_with_ext ;
if(!move_uploaded_file($file_tmp, $source)) {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$file[] = NULL;
}else{
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($sExt) {
case '.gif':
$simg = imagecreatefromgif($source);
break;
case '.jpg':
$simg = imagecreatefromjpeg($source);
break;
case '.png':
$simg = imagecreatefrompng($source);
break;
}
$dest = $thumb_directory. $file_name_with_ext ;
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
// imagewebp($dimg, $dest);
compress($source, "$desired_dir" . $file_name_with_ext , 50);
compress($dest, $dest , 50);
$file[] = $file_name_with_ext ;
}
}else{
// TODO: error handling
}
}
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file[0], PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file[1], PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file[2], PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file[3], PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: https://google.com');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
} else if ($targetRatio > $srcRatio) {
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
} else {
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
?>
As part of your question you asked if there was "any good and faster function to do please."
https://github.com/delboy1978uk/image
Try this! (install via Composer or just require each of the classes in if you just drop the code in yourself)
<?php
use Del\Image;
$image = new Image('/path/to/your.jpg'); //or gif , etc
// Or...
$image = new Image();
$image->load('/path/to/my.png');
You'll then have all of these commands at your disposal:
$image->crop($width, $height, 'center'); // Crops the image, also accepts left or right as 3rd arg
$image->destroy(); // remove loaded image in the class. Frees up any memory
$image->getHeader(); // returns image/jpeg or equivalent
$image->getHeight(); // returns height in pixels
$image->getWidth(); // returns width in pixels
$image->output(); // output to browser
$image->output(true); // passing true returns raw image data string
$image->resize($width, $height); // resize to the given dimensions
$image->resizeAndCrop($width, $height); // resize to the given dimensions, cropping top/bottom or sides
$image->save(); // Save the image
$image->save('/path/to/save.jpg', $permissions, $compression); // Save as a different image
$image->scale(50); // Scale image to a percentage
Loop through your POSTed uploads, load them up, save the original, resize the image, and save the thumbnail. Existing images shouldn't be touched.
There are plenty bad php-programming-habits in that code (e.g. use of eval and general data-flow).
To break it down: The script first validates the uploaded files and moves them to a temp directory. Then it calculates thumbnails for all files in the temp directory.
To change that we use an array which contains the filenames of uploading images.
// ...
$file_type = array();
$ext = '';
$title = '';
$i = 0;
// First change:
$validFileNames = array_column($uploadedFiles, 0);
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..' || !in_array($file_name, $validFileNames)) {
continue;
}
// Nothing changed beyond this point
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
// ...
}
array_column($uploadedFiles, 0) reads the index 0 of every entry in $uploadedFiles, which contains the filename. So $validFileNames contains only filenames of uploading images.
We then check for every file in the temp-directory if its name is included in $uploadedFiles. If not then it was not uploading and can be ignored.
As for the request of a more general optimization:
<?php
$desired_dir = $_SERVER['DOCUMENT_ROOT'].'/upload/file/';
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $uploadedFileName) {
$errors = array();
$destFilename = md5(uniqid('uploads', true).time());
$uploadedSize = $_FILES['files']['size'][$key];
$uploadedTmpName = $uploadedFileName;
$uploadedType = $_FILES['files']['type'][$key];
$sExt = null;
if ($uploadedType == 'image/gif') {
$sExt = '.gif';
} elseif ($uploadedType == 'image/jpeg' || $uploadedType == 'image/pjpeg') {
$sExt = '.jpg';
} elseif ($uploadedType == 'image/png' || $uploadedType == 'image/x-png') {
$sExt = '.png';
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = 'Image types alowed are (.gif, .jpg, .png) only!';
}
if ($uploadedSize > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (!empty($errors)) {
// Todo: Error handling of $errors
continue;
}
if (is_dir($desired_dir) == false) {
mkdir($desired_dir, 0700);
}
$destFilePath = "$desired_dir/".$destFilename.$sExt;
if (!move_uploaded_file($uploadedTmpName, $destFilePath)) {
echo "Couldn't upload file ".$uploadedTmpName;
}
$nw = 125;
$nh = 90;
$source = $destFilePath;
$stype1 = explode('.', $source);
$stype = $stype1[count($stype1) - 1];
$dest = $_SERVER['DOCUMENT_ROOT'].'/upload/thumb/'.$destFilename.$sExt;
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
compress($source, "$desired_dir/".$file_name, 50);
$uploadedFiles[] = $destFilePath;
}
$stmt = $conn->prepare('INSERT INTO allpostdata(im1, im2, im3, im4)'
.' VALUES (?, ?, ?, ?)');
if ($stmt->execute($uploadedFiles)) {
header('Location: /post/price_plan.php');
}
}
exit;
}

Not a valid PNG file

I have a code:
<?php
$size = 2000000;
$types = array('image/png', 'image/jpeg');
if(isset($_POST['go'])){
$newName = $id . '.' . $type;
$directory = 'img/avatars/'; //path to folder with images
$picture = $directory . basename($newName);
if (!in_array($_FILES['picture']['type'], $types)) {
die('Wrong type of file. Try another');
} elseif ($_FILES['picture']['size'] > $size) {
die('File is too big. Try another');
} elseif (move_uploaded_file($_FILES['picture']['tmp_name'], $picture)) {
echo "Image was downloaded!";
}
$new_width = 66; //necessary width
$size = getimagesize($picture);
$width = $size[0];
$height = $size[1];
if ($type == 'png') {
$src=ImageCreateFromPng($picture);
}
if ($type == 'jpeg' || $type == 'jpg') {
$src=ImageCreateFromJPEG($picture);
}
$coefficient = $width/$new_width;
$new_height = ceil($height/$coefficient);
$empty_picture = ImageCreateTrueColor($new_width, $new_height);
ImageCopyResampled($empty_picture, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if ($type == 'png') {
ImagePNG($empty_picture, $picture, -1);
}
if ($type == 'jpeg') {
ImageJPEG($empty_picture, $picture, -1);
}
imagedestroy($src);
}
?>
It returns an error:
imagecreatefrompng(): 'img/avatars/6.png' is not a valid PNG file in
W:\domains\mysite\settings.php
I checked is it png image:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $picture); // image/png
finfo_close($finfo);
And it returns me: image/png (it is).
So I do not know what is wrong with this code. Would be grateful for any help!

PHP thumbnail with white background and not centralized

I have the following php script to create thumbnail after uploading an image. It is working properly, but it creates a black background and does not center the image if it is not the size you want, does anyone know how to leave the white background and center it?
How to fix it
https://imgur.com/a/uTrPadZ
if($_SERVER['REQUEST_METHOD']=='POST')
{
$filetmp = $_FILES["image"]["tmp_name"];
$filename = $_FILES["image"]["name"];
$filetype = $_FILES["image"]["type"];
$filesize = $_FILES["image"]["size"];
$fileinfo = getimagesize($_FILES["image"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../uploads/";
$filepath_thumb = "../thumbnail/";
if($filetmp == "")
{
echo "please select a photo";
}
else
{
if($filesize > 2097152)
{
echo "photo > 2mb";
}
else
{
if($filetype != "image/jpeg" && $filetype != "image/png" && $filetype != "image/gif")
{
echo "Please upload jpg / png / gif";
}
else
{
$final_image = rand(1000,1000000).$filename;
$filepath = $filepath.strtolower($final_image);
move_uploaded_file($filetmp,$filepath);
if($filetype == "image/jpeg")
{
$imagecreate = "imagecreatefromjpeg";
$imageformat = "imagejpeg";
}
if($filetype == "image/png")
{
$imagecreate = "imagecreatefrompng";
$imageformat = "imagepng";
}
if($filetype == "image/gif")
{
$imagecreate= "imagecreatefromgif";
$imageformat = "imagegif";
}
$new_width = "200";
$new_height = "200";
$filepath_thumb = $filepath_thumb.strtolower($final_image);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = $imagecreate($filepath); //photo folder
if($filewidth > $fileheight)
{
$thumb_w = $new_width;
$thumb_h = $fileheight*($new_height/$filewidth);
}
if($filewidth < $fileheight)
{
$thumb_w = $filewidth*($new_width/$fileheight);
$thumb_h = $new_height;
}
if($filewidth == $fileheight)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($image_p,$image,0,0,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
}
}
}
}
Black is the default background, you just have to set the background colour of the new image to white first.
//set background colour white before copying
$white = imagecolorallocate($image_p, 255, 255, 255);
imagefill($image_p, 0, 0, $white);
imagecopyresampled($image_p,$image,0,0,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
Also, $dst_img doesn't appear to be used.
Centering (untested, but simple enough math):
$xOffset = (imagesx($p_image)-$thumb_w) / 2;
$yOffset = (imagesy($p_image)-$thumb_h) / 2;
imagecopyresampled($image_p,$image,$offsetX,$offsetY,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
If you know which dimension does not match the new thumbnail dimension this could be simplified.

How can i upload file with rename?

I have a file uploading code. everything is ok but i want to rename the file when it up loaded. my code is here. i need only the rename function and where it should be put. this code is very long because there crop the big image to small.
example: if file is 10MB it will be 40 or 50 KB
error_reporting(0);
$change = "";
$abc = "";
define("MAX_SIZE", "400");
function getExtension($str) {
$i = strrpos($str, ".");
if (!$i) {
return "";
} $l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$errors = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$image = $_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image) {
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$change = '<div class="msgdiv">Unknown Image extension</div>';
$errors = 1;
} else {
$size = filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE * 1024) {
$change = '<div class="msgdiv">You have exceeded the size limit!</div>';
$errors = 1;
} if ($extension == "jpg" || $extension == "jpeg") {
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
} else if ($extension == "png") {
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
} else {
$src = imagecreatefromgif($uploadedfile);
} echo $scr;
list($width, $height) = getimagesize($uploadedfile);
$newwidth = 280;
$newheight = ($height / $width) * $newwidth;
$tmp = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename = "../adimages/" . $_FILES['file']['name'];
imagejpeg($tmp, $filename, 100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
Just use the name you want instead of $_FILES['file']['name']
For example:
$filename = "../adimages/". time();
This will name each uploaded file with the current timestamp.
change Your below line
$filename = "../adimages/" . $_FILES['file']['name'];
with the below:-
$new_name = "new_file_name".time();
$filename = "../adimages/" . $new_name;
time() is added for uniqueness. and at the place of new_file_name , You can also put $_FILES['file']['name'];
try this --
just replace your line
$filename = "../adimages/" . $_FILES['file']['name'];
with this new line
$filename = "../adimages/" .time().'.'.$extension ;

Upload image with resize in php

I have a problem with image uploading in php
I want uploading with resizing image to width=600px
ex, when I uploaded an image with width of 2000px it should be uploaded with width of 600px
and of course smaller size on disk...
php file is:
<?php
require_once("db.php");
$name = trim($_POST['name']);
$addr = trim($_POST['addr']);
$dist = trim($_POST['dist']);
$city = trim($_POST['city']);
$phone = trim($_POST['phone']);
$price = trim($_POST['price']);
$lati = trim($_POST['lati']);
$long = trim($_POST['long']);
$tid = trim($_POST['type']);
$img = "";
if($_FILES)
{
//var_dump($_FILES);
$random_str = md5(uniqid(mt_rand(), true));
$f_name = "tmp/".$random_str.".jpg";
move_uploaded_file($_FILES['placeimg']['tmp_name'], $f_name);
$img = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$f_name;
$uploadedfile = $_FILES['placeimg']['tmp_name'];
$size=filesize($_FILES['placeimg']['tmp_name']);
$uploadedfile =$_FILES['placeimg']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($_FILES['placeimg']['tmp_name']);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
//$filename = "tmp/". $_FILES['file']['name'];
imagejpeg($tmp,$uploadedfile,75);
imagedestroy($src);
}
$sql = "INSERT INTO `Place`(`PName`, `PAddr`, `PDistrict`, `PCity`, `PImage`, `PPhone`, `PPrice`, `PLat`, `PLong`, `TID`, `PStatus`) VALUES ('{$name}', '{$addr}', '{$dist}', '{$city}', '{$img}', '{$phone}', '{$price}', '{$lati}', '{$long}', '{$tid}', '0')";
$status = 0;
$mess = "Err!";
if(mysql_query($sql))
{
$status = 1;
$mess = "Successful! Waiting approve";
}
$json['status'] = $status;
$json['message'] = $mess;
echo json_encode($json);
?>
the result is a big image without resizing
can you help?
try this:
function upload_resize($file,$newwidth,$resolution,$location,$prefix){
define ("MAX_SIZE","2048");
error_reporting(0);
$image =$file["name"];
$uploadedfile = $file['tmp_name'];
if ($image) {
$filename = stripslashes($file['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//Unknown Image extension
return 1;
}
else
{
$size=filesize($file['tmp_name']);
if ($size > MAX_SIZE*1024){
//You have exceeded the size limit
return 2;
}
if($extension=="jpg" || $extension=="jpeg" ) {
$uploadedfile = $file['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png") {
$uploadedfile = $file['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else {
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $location.$prefix.$file['name'];
imagejpeg($tmp,$filename,$resolution);
imagedestroy($src);
imagedestroy($tmp);
}
}
return 0;
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// get file from user and send to this function:
$res=upload_resize($_FILES["image"],600,100,'../images','');
switch ($res){
case 0 : echo 'images saved'; break;
case 1 : echo 'Unknown file type'; break;
case 2 : echo 'file size error'; break;
}
i use this function for upload and resize image.
// for outputting a jpeg image, Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Output the image
imagejpeg($tmp,$uploadedfile,75);
try this..
You create a new pattern file (using imagecreatetruecolor), but u didn't use a original picture.
Try use imagecopyresampled
like this:
<?php
require_once("db.php");
$name = trim($_POST['name']);
$addr = trim($_POST['addr']);
$dist = trim($_POST['dist']);
$city = trim($_POST['city']);
$phone = trim($_POST['phone']);
$price = trim($_POST['price']);
$lati = trim($_POST['lati']);
$long = trim($_POST['long']);
$tid = trim($_POST['type']);
$img = "";
if($_FILES)
{
//var_dump($_FILES);
$random_str = md5(uniqid(mt_rand(), true));
$f_name = "tmp/".$random_str.".jpg";
move_uploaded_file($_FILES['placeimg']['tmp_name'], $f_name);
$img = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$f_name;
$uploadedfile = $_FILES['placeimg']['tmp_name'];
$size=filesize($_FILES['placeimg']['tmp_name']);
$uploadedfile =$_FILES['placeimg']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($_FILES['placeimg']['tmp_name']);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$buff = imagecreatefromjpeg($uploadedfile);
imagecopyresampled($tmp, $b, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//$filename = "tmp/". $_FILES['file']['name'];
imagejpeg($tmp,$uploadedfile,75);
imagedestroy($src);
}
$sql = "INSERT INTO `Place`(`PName`, `PAddr`, `PDistrict`, `PCity`, `PImage`, `PPhone`, `PPrice`, `PLat`, `PLong`, `TID`, `PStatus`) VALUES ('{$name}', '{$addr}', '{$dist}', '{$city}', '{$img}', '{$phone}', '{$price}', '{$lati}', '{$long}', '{$tid}', '0')";
$status = 0;
$mess = "Err!";
if(mysql_query($sql))
{
$status = 1;
$mess = "Successful! Waiting approve";
}
$json['status'] = $status;
$json['message'] = $mess;
echo json_encode($json);
?>

Categories