I ran the code in apache localhost and also tried in my host. In both of them, the method moved the file but the file seemed 0kb.
Here is the code:
if(isset($_POST['upload'])){
if($_FILES['profile_foto']['size']>0&&$_FILES['profile_foto']['size']<102400){
$image_extension=explode("/",$_FILES['profile_foto']['type']);
if($image_extension[1]!="jpeg")
echo "<script type='text/javascript'>alert('The extension of the profile image must be jpeg!!!')</script>";
else{
if($_POST['image_id']==""){
$image_id= md5(uniqid());
$_FILES['profile_foto']['name']="tempo/".$image_id.".jpg";
move_uploaded_file($_FILES['profile_foto']['temp_name'],$_FILES['profile_foto']['name']);
list($width,$height)=getimagesize("tempo/".$image_id.".jpg");
if($width<=0||$width>170||$height<=0||$height>200){
$myFile="tempo/".$image_id.".jpg";
$fh=fopen($myFile,'w') or die("The File could not be opened!!!");
fclose($fh);
unlink($myFile);
echo "<script type='text/javascript'>alert('The width of your profile image must be less than 170 px, the height must be less than 200 px!!!')</script>";
}
else
$_POST['image_id']=$fotograf_id;
}
else{
$image_id= md5(uniqid());
$_FILES['profile_foto']['name']="tempo/".$image_id.".jpg";
move_uploaded_file($_FILES['profile_foto']['temp_name'],$_FILES['profile_foto']['name']);
list($width,$height)=getimagesize("tempo/".$image_id.".jpg");
if($width<=0||$width>170||$height<=0||$height>200){
$myFile="tempo/".$image_id.".jpg";
$fh=fopen($myFile,'w') or die("The File could not be opened!!!");
fclose($fh);
unlink($myFile);
echo "<script type='text/javascript'>alert('The width of your profile image must be less than 170 px, the height must be less than 200 px!!!')</script>";
}
else{
$image_will_be_deleted=$_POST['image_id'];
$myFile="tempo/".$image_will_be_deleted.".jpg";
$fh=fopen($myFile,'w') or die("The File cannot be opened!!!");
fclose($fh);
unlink($myFile);
$_POST['image_id']=$image_id;
}
}
}
}
else
echo "<script type='text/javascript'>alert('The size of the profile image must be less than 100 kb!!!')</script>";
}
You've posted about 50 lines of code when you claim only one isn't working. Strip out the 50 lines of code and replace it with:
move_uploaded_file($_FILES['profile_foto']['temp_name'],'tempo/test.jpg');
....and find out what happens when you try to upload a file.
C.
I think
$_FILES['profile_foto']['temp_name']
ought to be
$_FILES['profile_foto']['tmp_name']
in the statement
move_uploaded_file($_FILES['profile_foto']['temp_name'], $_FILES['profile_foto']['name']);
If you want a little function to conveniently resize you photos to whatever see below. if only $size1 is provided the image will be resized using this as its largest dimension, otherwise if $size2 is provided the image will be resized proportionally using $size1 as its largest dimension and then the rest is cropped. Might make it easier than your ($width<=0||$width>170||$height<=0||$height>200):
function resizeImg($name, $extension, $size1, $size2) {
if (preg_match('/jpg|jpeg/',$extension)){
$image = imagecreatefromjpeg($name);
}
if (preg_match('/gif/',$extension)){
$image = imagecreatefromgif($name);
}
$old_width = imageSX($image);
$old_height = imageSY($image);
$old_aspect_ratio = $old_width/$old_height;
if($size2 == 0){
$new_aspect_ratio = $old_aspect_ratio;
if($old_width > $old_height){
$new_width = $size1;
$new_height = $new_width / $old_aspect_ratio;
} else {
$new_height = $size1;
$new_width = $new_height * $old_aspect_ratio;
}
} elseif($size2 > 0){
$new_aspect_ratio = $size1/$size2;
//for landscape potographs
if($old_aspect_ratio >= $new_aspect_ratio) {
$new_width = $size1;
$new_height = $size2;
$x1 = round(($old_width - ($old_width * ($new_aspect_ratio/$old_aspect_ratio)))/2);
$old_width = round($old_width * ($new_aspect_ratio/$old_aspect_ratio));
$y1 = 0;
//for portrait photographs
} else{
$new_width = $size1;
$new_height = $size2;
$x1 = 0;
$y1 = round(($old_height/2) - ($new_height/2));
$old_height = round($old_width/$new_aspect_ratio);
}
}
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresized($new_image, $image, 0, 0, $x1, $y1, $new_width, $new_height, $old_width, $old_height);
return $new_image;
}
Related
I have been using the function below to resize image, but realized it does not work on images that are longer then the width. Current Image I'm testing is 1200 x 1800 and is 248kb. With this image the function does nothing to it. When loaded into the directory it not only is the same size 1200 x 1800, but is also still 248kb. I have simplfied the code and tested the code below and sure enough it's giving the same results. Any ideas?
function resize_image($file, $max_resolution){
if(file_exists($file)){
$original_image = imagecreatefromjpeg($file);
//resolution
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);
//try width first
$ratio = $max_resolution / $original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
//If that didnt work
if($new_height > $max_resolution){
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * ratio;
}
if($original_image){
$new_image = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_image,$original_image,0,0,0,0,$new_width,$new_height,$original_width,$original_height);
imagejpeg($new_image,$file,90);
}
}
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(isset($_FILES['image']) && $_FILES['image']['type'] == 'image/jpeg'){
print_r($_FILES);
move_uploaded_file($_FILES['image']['tmp_name'], $_FILES['image']['name']);
$file = $_FILES['image']['name'];
resize_image($file, "500");
echo "<img src='$file'/>";
}
}
?>
I'm using a url link to resize images, such as:
image.php?name=butterfly&size=1100x1100
for example:
<img src="image.php?name=butterfly&size=1100x1100">
The code I'm using is:
<?php
if(isset($_GET['name'])){ //name
$image['name'] = $_GET['name'];
} else {
$image['name'] = null;
}
if(isset($_GET['size'])){ //dimensions
$image['size'] = $_GET['size'];
$size = explode('x', $image['size']);
$image['width'] = $size[0];
$image['height'] = $size[1];
} else {
$image['size'] = null;
}
if(isset($_GET['text'])){ //text
$image['text'] = $_GET['text'];
} else {
$image['text'] = null;
}
// File and new size
$filename = 'images/'.$image["name"].'.jpeg';
// Content type
header('Content-Type: image/jpeg');
// Output
imagecreatefromjpeg($filename);
// Set a maximum height and width
$width = $image['width'];
$height = $image['height'];
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
My code works only for one part, which is the width, the image is resized to it's width but not height. Also when I resize my window, the picture get smaller every time. Thank you for your time and sorry for any bad explanation.
First of all, what is the question? I didn't get it.
One reason why the code changes only the width it may be because of this part of the code:
`if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}`
only one of the sizes will change. Also, another reasons why is changing only the width could be that you have as original image and quadratic resolution (e.g. 800x600 - ratio 1,34) and then you keep changing it to a wider one (e.g. 1280x720 - ratio 1,77).
Hope this helps!
As per your code logic, at any given time either your height or your width will change.
I tried it at my local host, width & height of my image was 600 X 400 and I passed 100X100 as parameter, it resized the image to 100X66, so the height did changed.
When i pass a black image background generated by imagecreatetruecolor to imagecopyresampled, its giving an error as parameter 1 in imagecopyresampled is expected to be resource but an integer given.
This is happening for gif images only. Also, i am using imagecolortransparent for gifs so that the animated ones do not appear as static with a black background but it also when is passed to imagecopyresampled gives the same error.
without imagecolortransparent:
function resizeImageGIF($image,$width,$height,$scale) {
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
$source = imagecreatefromgif($image);
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
imagegif($newImage,$image);
chmod($image, 0777);
return $image;
}
The above generates a static gif with black background and gives the same PHP error of integer given in parameter 1
With imagecolortransparent:
function resizeImageGIF($image,$width,$height,$scale) {
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
$black=imagecolorallocate($newImage,0,0,0);
$newImageTransparent = imagecolortransparent($newImage,$black);
$source = imagecreatefromgif($image);
imagecopyresampled($newImageTransparent,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
imagegif($newImageTransparent,$image);
chmod($image, 0777);
return $image;
}
this one generates an animated gif but still with the above error and also do not scale the images as a result image pops out of the fixed width container.
try this script and this script working for me
$size = 200; // the thumbnail height
$filedir = 'uploads/'; // the directory for the original image
$thumbdir = 'uploads/'; // the directory for the thumbnail image
$prefix = 'small0_'; // the prefix to be added to the original name
$maxfile = '2000000';
$mode = '0666';
$rnd_1 = rand(11111,99999);
$userfile_name= $rnd_1.'_'.$_FILES['image']["name"];
$userfile_tmp = $_FILES['image']['tmp_name'];
$userfile_size = $_FILES['image']['size'];
$userfile_type = $_FILES['image']['type'];
if (isset($_FILES['image']['name']))
{
$prod_img = $filedir.$userfile_name;
$prod_img_thumb = $thumbdir.$prefix.$userfile_name;
move_uploaded_file($userfile_tmp, $prod_img);
chmod ($prod_img, octdec($mode));
$sizes = getimagesize($prod_img);
$aspect_ratio = $sizes[1]/$sizes[0];
if ($sizes[1] <= $size)
{
$new_width = '500';
$new_height = '500';
}else{
$new_width = '500';
$new_height = '500';
}
$destimg=ImageCreateTrueColor($new_width,$new_height)
or die('Problem In Creating image');
$srcimg=ImageCreateFromJPEG($prod_img)
or $srcimg=ImageCreateFromPNG($prod_img)
or $srcimg=ImageCreateFromGIF($prod_img)
or die('Problem In opening Source Image0');
if(function_exists('imagecopyresampled'))
{
imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
or die('Problem In resizing');
}else{
Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
or die('Problem In resizing');
}
ImageJPEG($destimg,$prod_img_thumb,90)
or die('Problem In saving');
}
imagesavealpha($prod_img_thumb, true);
//setting completely transparent color
$transparent = imagecolorallocatealpha($prod_img_thumb, 0, 0, 0, 127);
//filling created image with transparent color
imagefill($prod_img_thumb, 0, 0, $transparent);
imagepng($prod_img_thumb);
}
I've made this piece of code, it will re-size images on the fly, if it can't find the requested image, and then stores it.
The only problem with this is that the output jpg image has a low quality.
I was wondering if there is something I need to change to improve the image quality.
if (isset($_GET['size'])) {
$size = $_GET['size'];
}
if (isset($_GET['name'])) {
$filename = $_GET['name'];
}
$filePath = "files/catalog/" . urldecode($filename);
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filePath);
if ($_GET["name"] && !$size) {
$newwidth = $width * $percent;
$newheight = $height * $percent;
} else if ($_GET["name"] && $size) {
switch ($size) {
case "thumbs":
$newwidth = 192;
$newheight = 248;
break;
case "large":
$newwidth = 425;
$newheight = 550;
break;
}
}
$resizedFileName = $filename;
$resizedFileName = str_replace(".jpg", "", $resizedFileName) . ".jpg";
$resizedFilePath = "files/catalog/" . urldecode($resizedFileName);
if (!file_exists($resizedFilePath)) {
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filePath);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb, $resizedFilePath);
//file_put_contents($, $binarydata);
$imageContent = file_get_contents($resizedFilePath);
echo $imageContent;
} else {
$imageContent = file_get_contents($resizedFilePath);
echo $imageContent;
}
Instead of imagecopyresized() you must use imagecopyresampled() and imagejpeg() function has third optional parameter and you can specify quality.
Probably because you are using imagejpeg() wrong, the second variable in the functions stands for the quality in percentage!
You want imagecopyresampled(). resize works by throwing away unecessary pixels. resampled() will average things out and produce much smoother results.
I have a php script which saves the original image, then resizes it - one thumbnail and one larger image for web viewing. This works well except with some images the quality is terrible. It seems to be saved with a very low colour pallet. You can see the result at http://kalpaitch.com/index.php?filter=white - click on the first thumbnail with the title 'white white white'
Below is the code used for the image resampling:
function resizeImg($name, $extension, $size1, $size2) {
if (preg_match('/jpg|jpeg|JPG|JPEG/',$extension)){
$image = imagecreatefromjpeg($name);
}
if (preg_match('/gif|GIF/',$extension)){
$image = imagecreatefromgif($name);
}
$old_width = imageSX($image);
$old_height = imageSY($image);
$old_aspect_ratio = $old_width/$old_height;
if($size2 == 0){
$new_aspect_ratio = $old_aspect_ratio;
if($old_width > $old_height){
$new_width = $size1;
$new_height = $new_width / $old_aspect_ratio;
} else {
$new_height = $size1;
$new_width = $new_height * $old_aspect_ratio;
}
} elseif($size2 > 0){
$new_aspect_ratio = $size1/$size2;
//for landscape potographs
if($old_aspect_ratio >= $new_aspect_ratio) {
$x1 = round(($old_width - ($old_width * ($new_aspect_ratio/$old_aspect_ratio)))/2);
$old_width = round($old_width * ($new_aspect_ratio/$old_aspect_ratio));
$y1 = 0;
$new_width = $size1;
$new_height = $size2;
//for portrait photographs
} else{
$x1 = 0;
$y1 = 0;
$old_height = round($old_width/$new_aspect_ratio);
$new_width = $size1;
$new_height = $size2;
}
}
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, $x1, $y1, $new_width, $new_height, $old_width, $old_height);
return $new_image;
Many Thanks
P.S.
[photos removed from server]
And here is the rest of the upload code:
// Move the original to the right place
$result = #move_uploaded_file($image['tmp_name'], $origlocation);
// Resize the image and save the thumbnail
$new_image = resizeImg($origlocation, $extension, 500, 0);
if (preg_match("/gif/",$extension)){
imagegif($new_image, $normallocation);
} else {
imagejpeg($new_image, $normallocation);
}
// Resize the image and save the thumbnail
$new_image = resizeImg($origlocation, $extension, 190, 120);
if (preg_match("/gif/",$extension)){
imagegif($new_image, $thumblocation);
} else {
imagejpeg($new_image, $thumblocation);
}
The loss in quality is down not to imagecopyresampled(), but to the JPEG compression. Unfortunately, GD's compression algorithms are no match to Photoshop's - in fact, very few are. But you can improve the result: GD's default JPG compression level is 75 of 100.
You can raise the quality using the third parameter to imagejpeg() (which I assume you are using for the final output):
imagejpeg ( $new_image, null, 99);
Play around in the 90-100 range. The image will become larger in file size than the original - that is going to be the price you pay. But it should be possible to achieve comparable quality.
Alternatively, as John Himmelman already says in the comments, try using imagepng() for better quality - also at the price of a notably larger file size, of course.
well, php.net documentation says you should have a imagecreatetruecolor() image for your dest_image if you want to avoid using only a 255 color palette but you already do that.
I guess an alternative would be to use an external tools such as imagemagick with a system() call.
The quick an dirty trick is to make the thumbnails 1000 x 1000 pixels (or more) on imagecopyresized() then set the JPEG quality to 20 or less on imagejpeg($img, $savePath, 20);. The output will usually be smaller than 100 kb.
Let the client CSS do the resizing and the pictures will be fast to load and look flawless in modern browsers when scaled to thumbnail size.
function img_resize( $tmpname, $size, $save_dir, $save_name, $maxisheight = 0 )
{
$save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
$gis = getimagesize($tmpname);
$type = $gis[2];
switch($type)
{
case "1": $imorig = imagecreatefromgif($tmpname); break;
case "2": $imorig = imagecreatefromjpeg($tmpname);break;
case "3": $imorig = imagecreatefrompng($tmpname); break;
default: $imorig = imagecreatefromjpeg($tmpname);
}
$x = imagesx($imorig);
$y = imagesy($imorig);
$woh = (!$maxisheight)? $gis[0] : $gis[1] ;
if($woh <= $size)
{
$aw = $x;
$ah = $y;
}
else
{
if(!$maxisheight)
{
$aw = $size;
$ah = $size * $y / $x;
}
else
{
$aw = $size * $x / $y;
$ah = $size;
}
}
$im = imagecreatetruecolor($aw,$ah);
if (imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y))
if (imagejpeg($im, $save_dir.$save_name))
return true;
else
return false;
}