Image Processing - Upload/Resize/Create Thumb & Save - php

I'm looking for some help.
I have the following code which uploads the image & creates a thumbnail and stores them in the appropriate folders... But my problem is space.. the uploaded main images are HUGE 4320 x 3240 and the site takes ages to load...
I only want 2 images: A main image max width 1024, and a thumbnail max width 100....
UPDATE: Now works and resizes main image and creates thumbnail but only works on small image sizes < 2500px wide... but I need it to work on an image 4320px wide....
here's my code so far:
<?php ob_start();
session_start();
include("../../config.php");
ini_set("memory_limit", "500M");
$folder = "../images/stock/".$_SESSION['info_id']."";
$thumbs =$folder.'/thumbs/';
if(!file_exists($folder)){
mkdir ($folder,0777);
$uploadfolder = $folder."/";
//echo $folder.'<br>';
}
else
{
//echo 'folder already created<br>';
$uploadfolder = $folder."/";
//echo $folder.'<br>';
}
if(!file_exists($thumbs)){
mkdir($thumbs,0777);
$thumbnailfolder = $thumbs ;
//echo $thumbs.'<br>';
}else{
$thumbnailfolder = $thumbs ;
//echo $thumbnailfolder.'<br>';
}
$allowedfiletypes = array("jpeg","jpg");
//$uploadfolder = $s;
$thumbnailheight = 100; //in pixels
$imagesresizeheight = 500;
$action = $_POST['action'];
if ($action == "upload") {
//$_SESSION['result'] = "Uploading image... " ;
if(empty($_FILES['uploadimage']['name'])){
$_SESSION['result'] = "<strong>Error: File not uploaded 1!</strong><br>" ;
} else {
$uploadfilename = $_FILES['uploadimage']['name'];
$fileext = strtolower(substr($uploadfilename,strrpos($uploadfilename,".")+1));
if (!in_array($fileext,$allowedfiletypes)) { $_SESSION['result'] = "<strong>Error: Invalid file extension!</strong><br>" ; }
else {
$fulluploadfilename = $uploadfolder.$uploadfilename ;
if (move_uploaded_file($_FILES['uploadimage']['tmp_name'], $fulluploadfilename)) {
$im = imagecreatefromjpeg($fulluploadfilename);
if (!$im) { $_SESSION['result'] = "<p><strong>Error: Couldn't Resize Image!</strong><br>" ; }
else {
//// Resize Image Creation //////
$imw = imagesx($im); // uploaded image width
$imh = imagesy($im); // uploaded image height
$nh = $imagesresizeheight; // thumbnail height
$nw = round(($nh / $imh) * $imw); //thumnail width
$newim = imagecreatetruecolor ($nw, $nh);
imagecopyresampled ($newim,$im, 0, 0, 0, 0, $nw, $nh, $imw, $imh) ;
$imagefilename = $uploadfolder.$uploadfilename ;
imagejpeg($newim, $imagefilename) or die($_SESSION['result'] ="<strong>Error: Couldn't save image resize!</strong><br>");
echo $imw. $imh. $nw. $imagefilename;
//// Thumbnail Creation //////
$imw = imagesx($im); // uploaded image width
$imh = imagesy($im); // uploaded image height
$nh = $thumbnailheight; // thumbnail height
$nw = round(($nh / $imh) * $imw); //thumnail width
$newim = imagecreatetruecolor ($nw, $nh);
imagecopyresampled ($newim,$im, 0, 0, 0, 0, $nw, $nh, $imw, $imh) ;
$thumbfilename = $thumbnailfolder.$uploadfilename ;
imagejpeg($newim, $thumbfilename) or die($_SESSION['result'] ="<strong>Error: Couldn't save thumnbail!</strong><br>");
//echo $thumbfilename;
//$_SESSION['result'] ='<img src="'.$thumbfilename.'"/><br>' ;
}
} else { $_SESSION['result'] = "<strong>Error: Couldn't save file($fulluploadfilename)!</strong><br>";
}
}
}
}
//unlink($fulluploadfilename);
////////////////////////////////////////////////
//connect to mysql server
$c = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB);
if (!$c){
$_SESSION['result'] .= mysql_error().'<br>';
return;
}
if (!mysql_select_db(DB)){
$_SESSION['result'] .= mysql_error().'<br>';
mysql_close($c);
return;
}
//5. insert settings
$sql = "INSERT INTO photo(photo_id,photo_filename) VALUES ('".$_SESSION['info_id']."','".$uploadfilename."')";
if (!mysql_query($sql,$c)){
mysql_close($c);
return;
}
mysql_close($c);
//////////////////////////////////////////////
//$ref = getenv("HTTP_REFERER");
//header("Location: ".$ref);
?>

just
unlink($fulluploadfilename);
after all thumbnails are created.

Related

Image Gallery passing variables to header location doesnot working?

This below mentioned code is written localhost/uploads/gallery.php file. I am including it in another page so it can be a part of header and footer including all my styling. I did it by include('uploads/gallery.php'); into a div.
Everything is working fine except the header location. When I go to the page where gallery is included which is "localhost/index.php?page=media"(localhost/views/media.php). It does not display thumbnails. I have to refresh the page to see thumbnails. Note: the code is written to display thumbnails when they are generated without refreshing the page.
My concern for asking question is, why i have to refresh page to load thumbnails. My header location is not passing variables correctly. I am a complete noob. please help me with this. Shukriya.
<?php
if(isset($_GET['img'])){
if(file_exists("uploads/{$_GET['img']}")) {
ignore_user_abort(true);
set_time_limit(120);
ini_set('memory_limit', '256M');
$src_image = getimagesize("uploads/{$_GET['img']}");
var_dump($src_image);
if($src_image === false) {
die("Wrong Image");
} # Wrong File Size
// Fixed Thumbnail Size
$thumb_width = 144;
$thumb_height = 144;
$thumb_ratio = round (($thumb_width / $thumb_height), 1);
$src_ratio = round (($src_image[0] / $src_image[1]), 1);
if ($src_ratio > $thumb_ratio) {
//Landescape Image dynamic width...
$new_size = array(($src_image[0] * $thumb_height)/$src_image[1], $thumb_height);
$new_pos = array(($new_size[0] - $thumb_width)/2,0);
} elseif ($src_ratio < $thumb_ratio) {
//PORTRAIT Image dynamic Height.....
$new_size = array($thumb_width, ($src_image[1] * $thumb_width)/$src_image[0]);
$new_pos = array(0, ($new_size[1] - $thumb_height)/2);
} elseif($src_ratio == $thumb_ratio) {
//Square
$new_size = array($thumb_width, $thumb_height);
$new_pos = array(0, 0);
}
if($new_size[0] < 1) $new_size[0] = 1;
if($new_size[1] < 1) $new_size[1] = 1;
$imgz = 'uploads/thumbs/'.$_GET['img'];
//GETTING Variable for Source image type. to create resample
if($src_image['mime'] === "image/jpeg"){
$src = imagecreatefromjpeg('uploads/'.$_GET['img']);
} elseif($src_image['mime'] === "image/png"){
$src = imagecreatefrompng('uploads/'.$_GET['img']);
} elseif($src_image['mime'] === "image/gif"){
$src = imagecreatefromgif('uploads/'.$_GET['img']);
}
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
imagecopyresampled($thumb, $src, 0,0, $new_pos[0], $new_pos[1], $new_size[0], $new_size[1], $src_image[0], $src_image[1]);
//GETTING Variable for Destination thumb image type. to create resample
if($src_image['mime'] === "image/jpeg"){
imagejpeg($thumb, $imgz);
} elseif($src_image['mime'] === "image/png"){
imagepng($thumb, $imgz);
} elseif($src_image['mime'] === "image/gif"){
imagegif($thumb, $imgz);
}
header("Location: uploads/thumbs/{$_GET['img']}");
} /* If file exists */ die();
} // ALL SCRIPT ENDED
if(is_dir('uploads/thumbs') === false) {
mkdir('uploads/thumbs', 0744);
} // Check & Create Directory
$images = glob('uploads/'.'*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
foreach($images as $image){
$imgs = 'uploads/thumbs/'.substr($image,8);
$nme = substr($image,8);
if(file_exists("$imgs")){
echo "<img src=\"$imgs\" alt=\"$nme\" class=\"img-thumbnail\" />"; //uploads/{$img} , data-toggle=\"modal\" data-target=\"#myModal\"
} else {
echo "<img src=\"?page=media&img=$nme\" alt=\"$nme\" class=\"img-thumbnail\" />";
}
}
?>

Image resize in php?

How can i resize proportionaly image in php without "squishing" ? I need some solution, i was searching here, but i could't find anything what i need.
What i have:
<?php
if (isset($_SESSION['username'])) {
if (isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg', '.jpeg', '.png', '.gif');
$max_filesize = 10485760;
$upload_path = 'gallery/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if (!in_array($ext, $allowed_filetypes)) {
die('The file you attempted to upload is not allowed.');
}
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
die('The file you attempted to upload is too large.');
}
if (!is_writable($upload_path)) {
die('You cannot upload to the specified directory, please CHMOD it to 777.');
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
}
echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';
echo ' <input type="file" name="userfile"/>';
echo ' <input type="submit" name="upload" value="Качи">';
echo ' </form>';
} else {
echo "<font color='#ec3f8c'>Съжелявам! За да качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>";
}
?>
I want to add something like this:Click here
how i call images?
echo '<a href="profiles.php?id='.$rowtwo['id'].'">';
echo"<img src='gallery/".$rowtwo['avatar']."' width='170px' height='217px'/>";
echo'</a>';
I save my image of avatar in DB in users as avatar.
It's much easier to use JS. It also works better because you're letting the client do the slow work of manipulation vs using your finite server resources for that task.
Here's a sample:
//This is the URL to your original image
var linkUrl = "http://www.mywebsite.com/myimage.png";
//This is a div that is necessary to trick JS into letting you manipulate sizing
//Just make sure it exists and is hidden
var img = $('#HiddenDivForImg');
//This is a call to the function
image_GetResizedImage(img, linkUrl);
//This function does the magic
function image_GetResizedImage(img, linkUrl) {
//Set your max height or width dimension (either, not both)
var maxDim = 330;
//Define the equalizer to 1 to avoid errors if incorrect URL is given
var dimEq = 1;
//This determines if the larger dimension is the images height or width.
//Then, it divides that dimension by the maxDim to get a decimal number for size reduction
if (img.height() > maxDim || img.width() > maxDim) {
if (img.height() > img.width()) {
dimEq = maxDim / img.height();
} else {
dimEq = maxDim / img.width();
}
}
var imageOutput = "<a href='" + linkUrl + "' target='_blank'>View Larger</a><br /><a href='" + result +
"' target='_blank'><img src='" + linkUrl + "' style='width: " + img.width() * dimEq
+ "px; height: " + img.height() * dimEq + "px' /></a>";
//This returns a URL for the image with height and width tags of the resized (non-squished) image.
return imageOutput;
}
For image manipulation in PHP you can use Imagemagick.
http://www.imagemagick.org/
It's the scale command you are looking for.
Here I have created a function with your reference link, you can use it like this
Call it
//Resize uploaded image
resize_image($_FILES['userfile'], 100, 200);
//Or if you want to save image with diffrent name
$filename = $upload_path.$_SESSION['username'].'-avatar.jpg';
resize_image($_FILES['userfile'], 100, 200, $newfilename);
//if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$filename."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
Function
function resize_image($image_src, $w = 100, $h = 100, $save_as = null) {
// Create image from file
switch(strtolower($image_src['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($image_src['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($image_src['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($image_src['tmp_name']);
break;
default:
exit('Unsupported type: '.$image_src['type']);
}
// Target dimensions
$max_width = $w;
$max_height = $h;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
if($save_as) {
//Save as new file
imagejpeg($new, $save_as, 90);
}else{
//Overwrite image
imagejpeg($new, $image_src['tmp_name'], 90);
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
}
I use http://image.intervention.io/. You can scale, cache, store, convert and do various image manipulation tasks.
Very easy to use.
// load the image
$img = Image::make('public/foo.jpg');
// resize the width of the image to 300 pixels and constrain proportions.
$img->resize(300, null, true);
// save file as png with 60% quality
$img->save('public/bar.png', 60);

How to integrate php thumbnail creator with multiple image uploader script?

I have this code to upload multiple image. It is working fine.
<?php
include('db.php');
session_start();
$session_id='1'; //$session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$inputFileName = $_FILES['photoimg']['name'];
$actual_image_name = time().substr(str_replace(" ", "_", $ext), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
But I want to create thumbnail for per image. To do this I have another one. I have found it from a website...but I can't understand how to integrate with my original one.
function thumbnail($inputFileName, $maxSize = 100)
{
$info = getimagesize($inputFileName);
$type = isset($info['type']) ? $info['type'] : $info[2];
// Check support of file type
if ( !(imagetypes() & $type) )
{
// Server does not support file type
return false;
}
$width = isset($info['width']) ? $info['width'] : $info[0];
$height = isset($info['height']) ? $info['height'] : $info[1];
// Calculate aspect ratio
$wRatio = $maxSize / $width;
$hRatio = $maxSize / $height;
// Using imagecreatefromstring will automatically detect the file type
$sourceImage = imagecreatefromstring(file_get_contents($inputFileName));
// Calculate a proportional width and height no larger than the max size.
if ( ($width <= $maxSize) && ($height <= $maxSize) )
{
// Input is smaller than thumbnail, do nothing
return $sourceImage;
}
elseif ( ($wRatio * $height) < $maxSize )
{
// Image is horizontal
$tHeight = ceil($wRatio * $height);
$tWidth = $maxSize;
}
else
{
// Image is vertical
$tWidth = ceil($hRatio * $width);
$tHeight = $maxSize;
}
$thumb = imagecreatetruecolor($tWidth, $tHeight);
if ( $sourceImage === false )
{
// Could not load image
return false;
}
// Copy resampled makes a smooth thumbnail
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $tWidth, $tHeight, $width, $height);
imagedestroy($sourceImage);
return $thumb;
}
/**
* Save the image to a file. Type is determined from the extension.
* $quality is only used for jpegs.
* Author: mthorn.net
*/
function imageToFile($im, $fileName, $quality = 80)
{
if ( !$im || file_exists($fileName) )
{
return false;
}
$ext = strtolower(substr($fileName, strrpos($fileName, '.')));
switch ( $ext )
{
case '.gif':
imagegif($im, $fileName);
break;
case '.jpg':
case '.jpeg':
imagejpeg($im, $fileName, $quality);
break;
case '.png':
imagepng($im, $fileName);
break;
case '.bmp':
imagewbmp($im, $fileName);
break;
default:
return false;
}
return true;
}
$im = thumbnail('temp.jpg', 100);
imageToFile($im, 'temp-thumbnail.jpg');
Help will be greatly appreciated...
You can use following;
<?php
....
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
// Create thumbnail here
$thumb = thumbnail($path.$actual_image_name, "80"); // image name, and size
imageToFile($thumb, 'path/to/thumb/thumbnail_' . $session_id . '.jpg');
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
...
?>
Do not forget to add thumbnail and imageToFile to put in your php file
<?php
// thumbnail configuration
$thumb_width = 50;
$thumb_height = 50;
$thumb_method = 'crop';
$thumb_bgColour = null; //array(255,240,240);
$thumb_quality = 70;
// Let script run for as long as it needs to when creating thumbnails.
// Some web hosts won't let you use this function. In that case you'll need
// to comment it out and just refresh the script until it has thumbnailed all the images.
set_time_limit(0);
// include the thumbnail function
require_once dirname(__FILE__) . '/paGdThumbnail.php';
// get the path to the current directory
$path = dirname(__FILE__);
// get the url for the images
$path_info = pathinfo($_SERVER['SCRIPT_NAME']);
$url = $path_info['dirname'];
// create an array to store image names in.
$images = array();
//$dir = new DirectoryIterator($path);
$file_name=$_REQUEST['big_img'];//$_FILES['big_img']['name'];
$file_path=$path.'\\'.$file_name;
/*
Loop through the directory, finding all images that aren't thumbnails.
For each image:
- if it doesn't already have a thumbnail, or the thumbnail is older than the image,
create a thumbnail.
- get info about the image
- add the image to our images array
*/
if( preg_match('#^(.+?)(_t)?\.(jpg|gif|png)#i', $file_name, $matches)){
list( ,$name, $is_a_thumb, $extension) = $matches;
// if its not a thumbnail
if( !$is_a_thumb ){
// does a valid thumbnail exist?
$has_thumb = false;
$thumb_file = $path . '/' . $matches[1] . '_t.jpg';
if( file_exists($thumb_file) && filemtime($thumb_file) > filemtime($file_path) ){
$has_thumb = true;
}
else{
// no thumbnail, so we shall create one!
// create a gd image. reading the contents of the image file into a string, then
// using imagecreatefromstring saves having to check the filetype and which
// imagecreatefrom(jpeg/gif/png) function to use
$image = imagecreatefromstring(file_get_contents($file_path));
if( $image ){
// create the thumbnail
$thumb = paGdThumbnail($image, $thumb_width, $thumb_height, $thumb_method, $thumb_bgColour);
// free the image resource
imagedestroy($image);
if( $thumb ){
// save the thumbnail
if( imagejpeg($thumb, $thumb_file, $thumb_quality) ){
$has_thumb = true;
}
// free the memory used by the thumbnail image
imagedestroy($thumb);
}
}
}
if( $has_thumb ){
$images[$file_name] = $name;
}
}
}
// sort the images array so always in the same order
ksort($images);
// end or processing, now display the gallery
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Thumbnails :</title>
<style type="text/css">
<!--
#thumbs{
position: relative;
}
#thumbs div{
float: left;
width: <?php echo $thumb_width + 30?>px;
height: <?php echo $thumb_height + 30?>px;
text-align: center;
}
#thumbs a:link img, #thumbs a:visited img{
border: 1px solid #acacac;
padding: 5px;
}
#thumbs a:hover img{
border: 1px solid black;
}
-->
</style>
</head>
<body>
<div id="thumbs">
<?php foreach( $images as $imagename => $name ){ ?>
<div>
<img src="<?php echo $url . '/' . $name . '_t.jpg'?>" />
</div>
<?php }?>
</div>
</body>
</html>

Image upload with resize

i have a upload script and that works fine, but i want that its upload twice, one orginal format and one in a thubm size.
I did allready search on google and stackoverflow and i tried allready something, but i dont get it work.
My upload script
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
include('./../includes/core.php');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Alleen '.implode(',',$allowed_ext).' bestanden zijn toegestaan');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
$name = $pic['name'];
$sname = hashing($name);
$datum = date("d-m-Y");
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$sname)){
mysql_query("INSERT INTO foto VALUES ('','".$pic['name']."','".$sname."', '".$datum."', '0')");
exit_status('Bestand succesvol geupload');
}
}
exit_status('Er is iets mis gegaan!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function hashing($naam){
$info = pathinfo($naam);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$hash = basename($naam, $ext);
$hash = $hash . genRandomstring();
$hash = md5($hash);
$hash = $hash . '-' . genRandomstring();
return $hash . $ext;
}
function genRandomString() {
$length = 5;
$string = "";
$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-+!#"; // change to whatever characters you want
while ($length > 0) {
$string .= $characters[mt_rand(0,strlen($characters)-1)];
$length -= 1;
}
return $string;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
If someone can help me? I will be very happy then becuase i have allready try this for a week and i can get it out.
Thanks, Chris
You have the image uploaded once, which is all you need, then use that to create the second thumbnail file.
Try looking over the GD documentation.
as mentioned before you don't need to upload twice, copy and resize image once it's uploaded like this:
$pathToImages = "path/to/images"
$pathToThumbs = "path/to/thumbs"
$fname = "image-file-name";
$new_fname = "thumb-file-name";
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
$thumbWidth = //someValue//;
$thumbHeight = //someValue//;
// calculate thumbnail size
$new_height = floor($height * ($thumbWidth/$width));
$new_width = $thumbWidth;
// create a new temporary image
$tmp_img = imagecreatetruecolor($thumbWidth, $thumbHeight);
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$new_fname}" );

unable to save image php

I have a snippet of code used to upload images into my gallery. All seems to work until it gets to the last part of the code.
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$pubID = $_POST['pubID'];
$size = 260; // the thumbnail height
$filedir = '../images/gallery/'.$pubID.'/'; // the directory for the original image
$thumbdir = '../images/gallery/'.$pubID.'/thumb/'; // the directory for the thumbnail image
$maxfile = '2000000';
$mode = '0777';
$userfile_name = $_FILES['Gallimage']['name'];
$userfile_tmp = $_FILES['Gallimage']['tmp_name'];
$userfile_size = $_FILES['Gallimage']['size'];
$userfile_type = $_FILES['Gallimage']['type'];
if (isset($_FILES['Gallimage']['name']))
{
$prod_img = $filedir.$userfile_name;
$prod_img_thumb = $thumbdir.$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 = $sizes[0];
$new_height = $sizes[1];
}else{
$new_height = $size;
$new_width = abs($new_height/$aspect_ratio);
}
$destimg=ImageCreateTrueColor($new_width,$new_height)
or die('Problem In Creating image');
$srcimg=ImageCreateFromJPEG($prod_img)
or die('Problem In opening Source Image');
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');
imagedestroy($destimg);
}
The error arrives on this line: ImageJPEG($destimg,$prod_img_thumb,90).
Here is the error code line 84 being the : ImageJPEG($destimg,$prod_img_thumb,90)
Warning: imagejpeg() [function.imagejpeg]: Unable to open '../images/gallery/264/thumb/Hair-Salon-1.jpg' for writing: No such file or directory in /home/www/public_html/console/gallery.php on line 84. Problem In saving
It's conceivable that the directory '../images/gallery/'.$pubID.'/thumb/' does not exist. Try to use mkdir('../images/gallery/'.$pubID.'/thumb/', 0775, true) and see what happens. This should create writable directories along the path, down to thumb at the end.
Try this code with a bit more error checking, a few corrections and some general improvements. Everything commented, if you don't understand anything just ask:
// Try not to over-use parenthesis, it makes code less readable. You only need them to group conditions.
if (isset($_POST["MM_insert"]) && $_POST["MM_insert"] == "form1") {
// Pass through basename() for sanitization
$pubID = basename($_POST['pubID']);
$size = 260; // the thumbnail height
$filedir = '../images/gallery/'.$pubID.'/'; // the directory for the original image
$thumbdir = '../images/gallery/'.$pubID.'/thumb/'; // the directory for the thumbnail image
$maxfile = '2000000';
// PHP understands proper octal representations - no need to turn it into a string
$mode = 0777;
if (isset($_FILES['Gallimage']['name'])) {
// Get upload info and create full paths
$userfile_name = $_FILES['Gallimage']['name'];
$userfile_tmp = $_FILES['Gallimage']['tmp_name'];
$userfile_size = $_FILES['Gallimage']['size'];
$userfile_type = $_FILES['Gallimage']['type'];
$prod_img = $filedir.$userfile_name;
$prod_img_thumb = $thumbdir.$userfile_name;
// Create directories if they don't exist - this is the crux of your problem
if (!is_dir($filedir)) {
mkdir($filedir, $mode, TRUE)
or die('Unable to create storage directory');
}
if (!is_dir($thumbdir)) {
mkdir($thumbdir, $mode, TRUE))
or die('Unable to create thumb directory');
}
// Move it to the correct location and set permissions
move_uploaded_file($userfile_tmp, $prod_img)
or die('Unable to move file to main storage directory');
chmod($prod_img, $mode)
or die('Unable to set permissions of file');
// Get info about the image
$sizes = getimagesize($prod_img);
$aspect_ratio = $sizes[1] / $sizes[0];
if ($sizes[1] <= $size) {
$new_width = $sizes[0];
$new_height = $sizes[1];
} else {
$new_height = $size;
$new_width = abs($new_height / $aspect_ratio);
}
// Create image resources
$destimg = imagecreatetruecolor($new_width, $new_height)
or die('Problem in creating image');
$srcimg = imagecreatefromjpeg($prod_img)
or die('Problem in opening source Image');
// Manipulate the image
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');
}
// Save the thumbnail and destroy the resources
imagejpeg($destimg, $prod_img_thumb, 90)
or die('Problem in saving');
imagedestroy($destimg);
}
// More code here? If not, merge all of this into a single if block
}

Categories