Related
I am working on a project which multiple pages validation. My main issue is with the upload part of the code. What i am doing is when a user upload his images; i save them in a tempfolder then once form filled complete, i move the images from temp to mainfolder but before i want to resize the images before saving them in mainfolder.
How can i achieve that ?
I have tried myself but could not get it right.here is my code
i got this error : getimagesize(174349.jpg): failed to open stream: No such file or directory
imageuploaded.php
<?php
define('MAX_FILE_SIZE', 952070);
define('UPLOAD_DIR_TEMP', BASE_URI.'html/temp/');
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg','image/png');
if (array_key_exists('upload', $_POST)) {
foreach ($_FILES['image']['name'] as $number => $file) {
// replace any spaces in the filename with underscores
$file = str_replace(' ','_',$file);
$fileNom = pathinfo($_FILES['image']["name"][$number], PATHINFO_FILENAME);
$ext = pathinfo($_FILES['image']["name"][$number],PATHINFO_EXTENSION);
//$soruceimg = $_FILES['image']['tmp_name'];
//echo $file;
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;
// check that file is within the permitted size
if ($_FILES['image']['size'][$number] > 0 || $_FILES['image']['size'][$number] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image']['type'][$number]) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['image']['error'][$number]) {
case 0:
// get the date and time
ini_set('date.timezone', 'Africa/Abidjan');
$now = date('Y-m-d-His');
//$Nfilename = basename(substr($file,0,6).$now).".".$ext ." ";
$successes = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR_TEMP.$file);
if ($successes) {
$_SESSION['imgname']= $_FILES['image']['name'];
header('Location: test.php');
//echo $file;
}
else {
$resultfile[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$resultfile[] = "Error uploading $file. Please try again.";
default:
$resultfile[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['image']['error'][$number] == 4) {
$errNofile[] = 1;
}
else {
$resultfile[] = "$file cannot be uploaded. Maximum size: $max.Acceptable file types: gif, jpg, png.";
}
}
}
imageresize.php
$source = BASE_URI.'html/temp/';
define('THUMBS_DIR', BASE_URI.'html/products/thumbs/');
define('MAX_WIDTH', 200);
define('MAX_HEIGHT', 200);
define('UPLOAD_DIR', BASE_URI.'html/products/');
ini_set('date.timezone', 'Africa/Abidjan');
$now = date('Y-m-d-His');
if (isset($_SESSION['imgname']) && is_array($_SESSION['imgname']) ) {
foreach ($_SESSION['imgname'] as $files) {
echo $files;
$img = str_replace(" ", "_", $files);
$ext = pathinfo($img,PATHINFO_EXTENSION);
if (file_exists($source.$img)) {
$ext = pathinfo($img,PATHINFO_EXTENSION);
// strip the extension off the image filename
$imagetypes = array('/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/');
$name = preg_replace($imagetypes, '', basename(substr($img,0,6).$now));
list($width, $height, $type) = getimagesize($img);
if ($width != $height) {
echo "file width and height must be same";
break;
}
elseif ( $width < 300 && $height < 300) {
echo "File must be at least 400 x 400";
break;
}
else{
$ratio = 1;
$ratio = MAX_WIDTH/$width;
}
$Nfilename = $name.'.'.$ext;
$moved = rename($source.$img, UPLOAD_DIR.$Nfilename);
if (!$moved) {
echo "Problem moving file".$img;
}
else{
// create an image resource for the original
switch($type) {
case 1:
$source = # imagecreatefromgif($original);
if (!$source) {
$result = 'Cannot process GIF files. Please use JPEG or PNG.';
}
break;
case 2:
$source = imagecreatefromjpeg($original);
break;
case 3:
$source = imagecreatefrompng($original);
break;
default:
$source = NULL;
$result = 'Cannot identify file type.';
}
// make sure the image resource is OK
if (!$source) {
$result = 'Problem copying original';
}
else {
// calculate the dimensions of the thumbnail
$thumb_width = round($width * $ratio);
$thumb_height = round($height * $ratio);
// create an image resource for the thumbnail
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
// create the resized copy
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
// save the resized copy
switch($type) {
case 1:
if (function_exists('imagegif')) {
$success = imagegif($thumb, THUMBS_DIR.$name.'_thb.gif');
$thumb_name = $name.'_thb.gif';
}
else {
$success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 50);
$thumb_name = $name.'_thb.jpg';
}
break;
case 2:
$success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 100);
$thumb_name = $name.'_thb.jpg';
break;
case 3:
$success = imagepng($thumb, THUMBS_DIR.$name.'_thb.png');
$thumb_name = $name.'_thb.png';
}
if ($success) {
$result = "$thumb_name created";
}
else {
$result = 'Problem creating thumbnail';
}
if ($success) {
echo $thumb_name;
}
// remove the image resources from memory
imagedestroy($source);
imagedestroy($thumb);
}
}
}
else{
echo "No file exist";
}
}
}
Convert the image to bitmap first and use bitmap compression with defined ratio to compress the size.
you can compress the image by declaring specific height and width also.
I had this code before, very easy to use, it works for me
class SimpleImage {
var $image; var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); }
elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); }
elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); }
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); }
elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); }
elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); }
if( $permissions != null) { chmod($filename,$permissions); }
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); }
elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); }
elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); }
}
function getWidth() { return imagesx($this->image); }
function getHeight() { return imagesy($this->image); }
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio; $this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio; $this->resize($width,$height);
}
function scale($scale) { $width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100; $this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image; }
}
Use it as prev image, and save new image
$imageRes = new SimpleImage();
$imageRes->load($_SERVER['DOCUMENT_ROOT'] . '/upload/' . $image . '.jpg');//prev image
$imageRes->resizeToWidth(120);
$imageRes->save($_SERVER['DOCUMENT_ROOT'] . '/upload/' . $image . '.jpg');//new image
What code would I use to:
Resize all images being uploaded to 600px width while maintaining aspect ratio for height
Rename the file being uploaded to the current time-stamp
and how exactly would I add that to or edit my existing code (preferably without using classes):
$target_dir2 = "creature_pics/";
$target_file2 = $target_dir2 . basename($_FILES["u_c2pic"]["name"]);
$uploadOk2 = 1;
$imageFileType2 = pathinfo($target_file2,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check2 = getimagesize($_FILES["u_c2pic"]["tmp_name"]);
if($check2 !== false) {
$uploadOk2 = 1;
} else {
$uploadOk2 = 0;
}
}
if (file_exists($target_file2)) {
$uploadOk2 = 0;
}
if ($_FILES["u_c2pic"]["size"] > 5000000) {
$uploadOk2 = 0;
}
if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg"
&& $imageFileType2 != "gif" ) {
$uploadOk2 = 0;
}
if ($uploadOk2 == 0) {
$ercode2 = "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["u_c2pic"]["tmp_name"], $target_file2)) {
} else {
$ercode2 = "Sorry, there was an error uploading your file.";
}
}
I'm new to php coding and would like the simplest solution possible.
If you can use Imagick on your server then the following code should help you out.
First the function to do the resizing.
if(!defined('APPLICATION_PATH')) define('APPLICATION_PATH', dirname(__FILE__));
function popupImage($width, $height, $code, $name) {
$file = APPLICATION_PATH.'/creature_pics/'.$name.'.jpg';
$im = new Imagick($file);
$imageprops = $im->getImageGeometry();
$r_width = $imageprops['width'];
$r_height = $imageprops['height'];
if($width > $height){
$newHeight = $height;
$newWidth = ($width / $r_height) * $r_width;
}else{
$newWidth = $width;
$newHeight = ($height / $r_width) * $r_height;
}
$im->resizeImage($newWidth,$newHeight, imagick::FILTER_LANCZOS, 0.9, true);
$im->cropImage ($width,$height,0,0);
$im->writeImage(APPLICATION_PATH.'/creature_pics/'.$code.'.jpg');
$im->destroy();
$newFile = APPLICATION_PATH.'/creature_pics/'.$code.'.jpg';
}
then in your code just add
if (move_uploaded_file($_FILES["u_c2pic"]["tmp_name"], $target_file2)) {
//This is the new line calling the function
$timestamp = microtime(true);
$newFile = popupImage(600,1200,$timestamp,$_FILES["u_c2pic"]["tmp_name"]);
} else {
$ercode2 = "Sorry, there was an error uploading your file.";
}
That should create a new file in /creature_pics/ which will be named something like 142023023.9777.jpg which is the timestamp passed into the function as the code.
EDIT
Missed the timestamp element so this is now added in
I'm trying to crop an image when it has been uploaded. So far I've only managed to resize it but if an image is a rectangular shape then the image is squashed which doesn't look nice. I'm trying to get coding that I can use with the function that I currently have to resize. The ones that I'm seeing I have to change my function and I'm hoping not to do that.
Here is my function
function createThumbnail($filename) {
global $_SITE_FOLDER;
//require 'config.php';
$final_width_of_image = 82;
$height = 85;
$path_to_image_directory = $_SITE_FOLDER.'portfolio_images/';
$path_to_thumbs_directory = $_SITE_FOLDER.'portfolio_images/thumbs/';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
//$ny = $height;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
Here is my function.
<?php
function crop($file_input, $file_output, $crop = 'square',$percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
echo 'Unable to get the length and width of the image';
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
echo 'Incorrect file format';
return;
}
if ($crop == 'square') {
$min = $w_i;
if ($w_i > $h_i) $min = $h_i;
$w_o = $h_o = $min;
} else {
list($x_o, $y_o, $w_o, $h_o) = $crop;
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
$x_o *= $w_i / 100;
$y_o *= $h_i / 100;
}
if ($w_o < 0) $w_o += $w_i;
$w_o -= $x_o;
if ($h_o < 0) $h_o += $h_i;
$h_o -= $y_o;
}
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopy($img_o, $img, 0, 0, $x_o, $y_o, $w_o, $h_o);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
And you can call like this
crop($file_input, $file_output, $crop = 'square',$percent = false);
And also resize function if you need.
<?php
function resize($file_input, $file_output, $w_o, $h_o, $percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
return;
}
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
}
if (!$h_o) $h_o = $w_o/($w_i/$h_i);
if (!$w_o) $w_o = $h_o/($h_i/$w_i);
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopyresampled($img_o, $img, 0, 0, 0, 0, $w_o, $h_o, $w_i, $h_i);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
resize($file_input, $file_output, $w_o, $h_o, $percent = false);
You can use SimpleImage class found here SimpleImage
[edit] Updated version with many more features here SimleImage Updated
I use this when resizing various images to a smaller thumbnail size while maintaining aspect ratio and exact image size output. I fill the blank area with a colour that suits the background for where the image will be placed, this class supports cropping. Explore the methods cutFromCenter and maxareafill.
For example in your code you would not need to imagecreatefromjpeg() you would simply;
Include the class include('SimpleImage.php');
then;
$im = new SimpleImage();
$im->load($path_to_image_directory . $filename);
$im->maxareafill($output_width,$output_height, 0,0,0); // rgb
$im->save($path_to_image_directory . $filename);
I use this class daily and find it very versatile.
I have below function to save JPEG as Progressive JPEG. It saved, but not as progressive JPEG. Is this correct ?
function save($filename, $image_type = IMAGETYPE_JPEG, $compression = 75, $permissions = null) {
if ($image_type == IMAGETYPE_JPEG) {
imageinterlace($this->image, true); //convert to progressive ?
imagejpeg($this->image, $filename, $compression);
} elseif ($image_type == IMAGETYPE_GIF) {
imagegif($this->image, $filename);
} elseif ($image_type == IMAGETYPE_PNG) {
imagepng($this->image, $filename);
}
if ($permissions != null) {
chmod($filename, $permissions);
}
}
This is how i called save() function :
function img_reconstruct($saveto) {
$image = new SimpleImage();
$image->load($saveto);
list($width, $height) = getimagesize($saveto);
if ($width > 800 && $width < 1200) {
$image->resize(800, $height);
$image->save($saveto);
}
}
try like below
imageinterlace($this->image, 1); //convert to progressive ?
may be issue with type casting
I am using directory iterator to iterate through directories and resize images found in that directory, I am doing this from browser cause I don't have ssh access to that server.
Most pictures resize fine but for every 10 pictures (more or less) I get jiberish data out.
I think it's a picture source. in that data there is always a string CREATOR: gd-jpeg v1.0 so I'm wondering what is this? I disabled any error output with # sign.
EDIT:
Here is the code, and also I disabled error output cause there aren't any errors and I thought that disabling error output would disable this jiberish data, but data is displayed no matter.
Code:
<?php
/*
big = 350
thumb = 90
thumb2 = 70
top = 215
*/
set_time_limit(0);
ini_set('memory_limit', '128M');
ini_set('display_errors', 'On');
class ResizeImages
{
private $dir = 'images/articles_backup_2009-12-19';
private $imageType = array(
'_big' => 'h:350',
'_thumb' => 'm:90',
'_thumb2' => 'h:70',
'_top' => 'h:215'
);
public function __construct()
{
$this->deleteImages();
$this->resizeImages();
}
private function resizeImages()
{
$n = 0;
$dh = opendir($this->dir);
while (($file = readdir($dh)) !== false)
{
if(is_dir($this->dir."/".$file) && $file != '.' && $file != '..')
{
echo $this->dir."/".$file.'<br />';
$deldir = opendir($this->dir."/".$file);
while (($filedel = readdir($deldir)) !== false)
{
if ($filedel != '.' && $filedel != '..' && $filedel != 'Thumbs.db')
{
$val = $this->resize($this->dir."/".$file."/".$filedel);
$n++;
}
}
}
}
closedir($dh);
}
private function resize($target)
{
$img = $target;
$origSize = getimagesize($img);
$origWidth = $origSize[0];
$origHeight = $origSize[1];
foreach($this->imageType as $key=>$value)
{
$attr = explode(':', $value);
if(strpos($attr[0], 'w') !== false)
{
$this->imageWidth = $attr[1];
$this->imageHeight = false;
}
if(strpos($attr[0], 'h') !== false)
{
$this->imageHeight = $attr[1];
$this->imageWidth = false;
}
$imageTmp = explode('.', $img);
if(count($imageTmp) == 2) $image_name_fin = $imageTmp[0].$key.'.'.$imageTmp[1];
else if(count($imageTmp) == 4) $image_name_fin = $imageTmp[0].'.'.$imageTmp[1].$key.'.'.$imageTmp[2];
if($this->imageWidth != false)
{
if($origWidth <= $this->imageWidth)
{
$resizeHeight = $origHeight;
$resizeWidth = $origWidth;
}
else
{
$resizeHeight = round($origHeight / ($origWidth / $this->imageWidth));
$resizeWidth = $this->imageWidth;
}
}
else if($this->imageHeight != false)
{
if($origHeight <= $this->imageHeight)
{
$resizeHeight = $origHeight;
$resizeWidth = $origWidth;
}
else
{
$resizeWidth = round($origWidth / ($origHeight / $this->imageHeight));
$resizeHeight = $this->imageHeight;
}
}
$im = ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = ImageCreateFromPNG ($img) or // or PNG Image
$im = ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
if (!$im)
{
$this->error = array(
'error' => true,
'notice' => 'UPLOADUNSUCCESSFULL'
);
return $this->error;
}
$thumb = ImageCreateTrueColor ($resizeWidth, $resizeHeight);
ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $resizeWidth, $resizeHeight, $origWidth, $origHeight);
ImageJPEG ($thumb, $image_name_fin, $this->imageQuality);
//echo $image_name_fin.'<br />';
}
$this->error = array(
'imageUrl' => $image_name,
'error' => false,
'notice' => 'IMAGEUPLOADED'
);
return $this->error;
}
private function deleteImages()
{
$dh = opendir($this->dir);
while (($file = readdir($dh)) !== false)
{
if(is_dir($this->dir."/".$file))
{
//echo $file.'<br />';
$deldir = opendir($this->dir."/".$file);
while (($filedel = readdir($deldir)) !== false)
{
if(strpos($this->dir."/".$file."/".$filedel, '_big.') !== false || strpos($this->dir."/".$file."/".$filedel, '_thumb.') !== false || strpos($this->dir."/".$file."/".$filedel, '_thumb2.') !== false || strpos($this->dir."/".$file."/".$filedel, '_top.') !== false)
{
unlink($this->dir."/".$file."/".$filedel);
}
}
}
}
closedir($dh);
}
}
$batch = new ResizeImages;
?>
At the top add this:
error_reporting(E_ALL);
And try changing this:
$im = ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = ImageCreateFromPNG ($img) or // or PNG Image
$im = ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
To this:
$im = ImageCreateFromString(file_get_contents($img));
Did it help? Also is there any pattern on the corrupted images? Are they all of the same type?
Well, the first thing would be to remove the error suppression to see if there is any errors. Seeing some of your code could be helpful as well.
EDIT
Ok, too late to fix your problem, but here is another suggestion for your code. All that "readdir, decide if file, build path" stuff is just a pain to use (and look at). Try this for an alternative:
class ImageFilterIterator extends FilterIterator
{
public function accept()
{
$ext = pathinfo($this->current()->getRealPath(), PATHINFO_EXTENSION);
return stripos('.gif|.jpg|.png', $ext);
}
}
$path = '.';
$images = new ImageFilterIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)));
Iterators are from the SPL and while they are somewhat puzzling to use at first, they can make development much easier once you understood them. With the above you can now loop over $image and get all filenames ending in .gif, .jpg or .png from all directories below path, like this:
foreach($images as $image) {
echo $image;
}
In fact, $image is not just a string, but an SplFileInfo object, so you also get a bunch of useful other methods with it.