I use a PHP file to upload images to my server from my web application and have recently hit some memory limit issues that I was hoping someone with more experience than me could help with. Most of the images uploaded have been from mobiles so the file size is very manageable but recently there have been some uploads from an SLR camera that have been causing the issues. These images are around 7-8MB in size and I had assumed our PHP memory limit of 64MB would handle this. Upon inspection I found the imagecreatefromjpeg() function in our crop function to be the culprit although I assume the memory has been filled up before this despite using imagedestroy() to clear any previously created images. Upon using ini_set('memory_limit') to up the limit to a much higher value I found the script worked as expected but I would prefer a cleaner solution. I have attached the code below and any help would be greatly appreciated.
ini_set('memory_limit', '256M');
if(isset($_POST)) {
############ Edit settings ##############
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$ThumbPrefix = "thumbs/"; //Normal thumb Prefix
$DestinationDirectory = '../../../uploads/general/'; //specify upload directory ends with / (slash)
$PortfolioDirectory = '../../../images/portfolio/';
$Quality = 100; //jpeg quality
##########################################
$imID = intval($_POST['imageID']);
$image = $_POST['image'];
$data = $image['data'];
$name = $image['name']; //get image name
$width = $image['width']; // get original image width
$height = $image['height'];// orig height
$type = $image['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
$desc = $image['desc'];
$album = intval($image['album']);
$customer = intval($image['customer']);
$tags = $image['tags'];
$allTags = $_POST['allTags'];
$portType = intval($image['portType']);
$rating = intval($image['rating']);
$imData = array();
if(strlen($data) < 500) {
$dParts = explode('?', $data);
$path = $dParts[0];
$base64 = file_get_contents($path);
$data = 'data:' . $type . ';base64,' . base64_encode($base64);
}
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
function base64_to_png($base64_string, $output_file) {
$img = str_replace('data:image/png;base64,', '', $base64_string);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$im = imagecreatefromstring($data);
if ($im !== false) {
imagepng($im, $output_file);
imagedestroy($im);
}
return $output_file;
}
if($stmt = $db -> prepare("UPDATE `images` SET name = ?, type = ?, description = ?, width = ?, height = ?, rating = ?, portType = ?, customer = ?, album = ?, dateModified = NOW() WHERE ID = ?")) {
$stmt -> bind_param("sssiiiiiii", $name, $type, $desc, $width, $height, $rating, $portType, $customer, $album, $imID);
if (!$stmt->execute()) {
echo false;
} else {
$delTags = "DELETE FROM tagLink WHERE imageID = $imID";
if(!$db->query($delTags)) {
echo $db->error;
}
if(sizeof($tags) > 0) {
foreach($tags as $tag) {
$tagQ = "INSERT INTO tagLink (imageID, tag) VALUES ($imID, '$tag')";
if(!$db->query($tagQ)) {
echo $db->error;
}
}
}
switch(strtolower($type))
{
case 'png':
$fname = $name . '(' . $imID . ').png';
$file = $DestinationDirectory . $fname;
$portfile = $PortfolioDirectory . $fname;
$thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
$CreatedImage = base64_to_png($data,$file);
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
$fname = $name . '(' . $imID . ').jpeg';
$file = $DestinationDirectory . $fname;
$portfile = $PortfolioDirectory . $fname;
$thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
$CreatedImage = base64_to_jpeg($data,$file);
break;
default:
die('Unsupported File!'); //output error and exit
}
array_push($imData, $imID);
array_push($imData, $name);
array_push($imData, $type);
array_push($imData, $portType);
echo json_encode($imData);
if(!cropImage($width,$height,$ThumbSquareSize,$thumbDest,$CreatedImage,$Quality,$type))
{
echo 'Error Creating thumbnail';
}
}
$stmt -> close();
} else {
/* Error */
printf("Prepared Statement Error: %s\n", $db->error);
}
/* Close connection */
$db -> close();
include '../cron/updatePortfolio.php';
}
//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$type)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
if($CurWidth>$CurHeight)
{
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}
switch(strtolower($type))
{
case 'png':
$imageX = imagecreatefrompng ( $SrcImage );
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
$imageX = imagecreatefromjpeg ( $SrcImage );
break;
default:
return false;
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $imageX, 0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
switch(strtolower($type))
{
case 'png':
imagepng($NewCanves,$DestFolder);
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
Look in the php.ini at
upload_max_filesize = 40M
post_max_size = 40M
Change 40M to your max size
Related
I need to inquire that i am using PHP class to upload single image. below I have the class and PHP code to upload image. it is working fine for single image upload, and Now I want to upload multiple image using the same class, I used for loop for this purpose and it gives some error. please brief where i am doing wrong
HTML for multiple images
<input type="file" name="photo[]" placeholder="Photo">
code for multiple images
for($i=0;$i<$count;$i++ ) {
if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
$uploadImage = new UploadImage;
echo $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
}
}
Below code is for single image upload which is working fine.
HTML
<input type="file" name="photo" placeholder="Photo">
code
if(isset($_FILES['photo']['tmp_name']) && ($_FILES['photo']['tmp_name']!="")){
$uploadImage = new UploadImage;
$obj['image'] = $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
}
Class.php
<?php
class UploadImage {
public function upload($imageField, $imageFieldIndex = null, $strLargePath = null, $largeWidth = 0, $largeHeight = 0, $strThumbPath = null, $thumbWidth = 0, $thumbHeight = 0)
{
$noLarge = false;
$noThumb = false;
if(empty($strLargePath)) {
$noLarge = true;
}
if(empty($strThumbPath)) {
$noThumb = true;
}
echo $fileName = isset($imageFieldIndex) ? stripslashes($_FILES[$imageField]['name'][$imageFieldIndex]) : stripslashes($_FILES[$imageField]['name']);
$fileTempName = isset($imageFieldIndex) ? $_FILES[$imageField]['tmp_name'][$imageFieldIndex] : $_FILES[$imageField]['tmp_name'];
$extension = $this->getExtension($fileName);
$imageName = time().$imageFieldIndex.'.'.$extension;
if($noLarge == false) {
$this->resize($largeWidth, $largeHeight, $fileTempName, $imageName, $strLargePath);
}
if($noThumb == false) {
$this->resize($thumbWidth, $thumbHeight,$fileTempName, $imageName, $strThumbPath);
}
return $imageName;
}
private function getExtension($strInput)
{
$i = strrpos($strInput,".");
if (!$i){return null;}
$j = strlen($strInput) - $i;
$output = substr($strInput, $i + 1, $j);
return $output;
}
private function resize($newWidth, $newHeight, $imageTempName, $imageName, $savePath) {
$image = new ResizeImage;
$image->newWidth = $newWidth;
$image->newHeight = $newHeight;
$image->imageTempName = $imageTempName; // Full Path to the file
$image->ratio = true; // Keep Aspect Ratio?
// Name of the new image (optional) - If it's not set a new will be added automatically
$image->imageName = substr($imageName, 0, strrpos($imageName, '.'));
/* Path where the new image should be saved. If it's not set the script will output the image without saving it */
$image->savePath = $savePath;
$process = $image->resize();
if($process['result'] && $image->savePath)
{
//echo 'The new image ('.$process['new_file_path'].') has been saved.';
}
}
}
/*-------------------------------- Image resize Class -----------------------------------------*/
class ResizeImage {
var $imageTempName;
var $newWidth;
var $newHeight;
var $ratio;
var $imageName;
var $savePath;
function resize(){
if(!file_exists($this->imageTempName)){
exit("File ".$this->imageTempName." does not exist.");
}
$info = GetImageSize($this->imageTempName);
if(empty($info)){
exit("The file ".$this->imageTempName." doesn't seem to be an image.");
}
$width = $info[0];
$height = $info[1];
$mime = $info['mime'];
/* Keep Aspect Ratio? */
$this->ratio = true;
if($this->ratio){
$thumb = ($this->newWidth < $width && $this->newHeight < $height) ? true : false; // Thumbnail
$largeImage = ($this->newWidth >= $width || $this->newHeight >= $height) ? true : false; // Large Image
if($thumb){
if($this->newWidth > $this->newHeight){
$x = ($width / $this->newWidth);
$this->newHeight = ($height / $x);
}else {
$x = ($height / $this->newHeight);
$this->newWidth = ($width / $x);
}
}else if($largeImage){
if($this->newWidth >= $width){
$x = ($this->newWidth / $width);
$this->newHeight = ($height * $x);
}
else if($this->newHeight >= $height){
$x = ($this->newHeight / $height);
$this->newWidth = ($width * $x);
}
}
}
// What sort of image?
$type = substr(strrchr($mime, '/'), 1);
switch ($type){
case 'jpeg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
break;
case 'jpg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
break;
case 'png':
$image_create_func = 'ImageCreateFromPNG';
$image_save_func = 'ImagePNG';
$newImageExt = 'png';
break;
case 'bmp':
$image_create_func = 'ImageCreateFromBMP';
$image_save_func = 'ImageBMP';
$newImageExt = 'bmp';
break;
case 'gif':
$image_create_func = 'ImageCreateFromGIF';
$image_save_func = 'ImageGIF';
$newImageExt = 'gif';
break;
case 'vnd.wap.wbmp':
$image_create_func = 'ImageCreateFromWBMP';
$image_save_func = 'ImageWBMP';
$newImageExt = 'bmp';
break;
case 'xbm':
$image_create_func = 'ImageCreateFromXBM';
$image_save_func = 'ImageXBM';
$newImageExt = 'xbm';
break;
default:
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
}
// New Image
$image_c = imagecreatetruecolor($this->newWidth, $this->newHeight);
$newImage = $image_create_func($this->imageTempName);
imagealphablending($image_c, false);
imagesavealpha($image_c,true);
$transparent = imagecolorallocatealpha($image_c, 255, 255, 255, 127);
imagefilledrectangle($image_c, 0, 0, $this->newWidth, $this->newHeight, $transparent);
ImageCopyResampled($image_c, $newImage, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height);
if($this->savePath)
{
if($this->imageName)
{
$new_name = $this->imageName.'.'.$newImageExt;
}
else
{
$new_name = $this->newImageName(basename($this->imageTempName)).'_resized.'.$newImageExt;
}
$save_path = $this->savePath.$new_name;
}
else
{
/* Show the image without saving it to a folder */
header("Content-Type: ".$mime);
$image_save_func($image_c);
$save_path = '';
}
$process = $image_save_func($image_c, $save_path);
return array('result' => $process, 'new_file_path' => $save_path);
}
function newImageName($filename)
{
$string = trim($filename);
$string = strtolower($string);
$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
$string = ereg_replace("[ \t\n\r]+", "_", $string);
$string = str_replace(" ", '_', $string);
$string = ereg_replace("[ _]+", "_", $string);
return $string;
}
}
?>
Add the image index to the upload function
for($i=0;$i<$count;$i++ ) {
if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
$uploadImage = new UploadImage;
echo $uploadImage->upload('photo', $i, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
//...................................^ here
}
}
I think this is the way it can be done.
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
And for the script you can upload multiple files using array.
Array
(
[0] => Array
(
[name] => foo.txt
[type] => text/plain
[tmp_name] => /tmp/phpYzdqkD
[error] => 0
[size] => 123
)
[1] => Array
(
[name] => bar.txt
[type] => text/plain
[tmp_name] => /tmp/phpeEwEWG
[error] => 0
[size] => 456
)
)
A quick function that would convert the $_FILES array to the cleaner (IMHO) array.
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
?>
Now I can do the following:
<?php
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
?>
Head over here for more explanation.
I have set up a simple "Facebook" like timeline system for my friend to be able to upload statuses with images for his users to see. It seemed to all be working well although the file which stores the images keeps being deleted, and I can't seem to purposely cause the problem myself so I have no idea what is removing this directory?
I have added the upload/remove scripts below to see if anybody might be able to assist me here? I can't seem to find any part of the script which would delete the main image directory on its own?
PLEASE BARE IN MIND - This is still unfinished, and is nowhere near secure just yet, we are in testing phase and need to fix this problem before I can work on perfecting the system.
The main folder for storage of the images is post_images, this is the directory which is being deleted.
REMOVE DIR FUNCTION -
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
}
rmdir($dir);
}
DECLINE POSTS -
if(isset($_GET['decline_post'])){
$post_id = $conn->real_escape_string($_GET['decline_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
DELETE POST -
if(isset($_GET['delete_post'])){
$post_id = $conn->real_escape_string($_GET['delete_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
UPLOAD POST -
if(isset($_POST['new_post'])){
$post_status = $conn->real_escape_string($_POST['status']);
$user_id = $_SESSION['user_id'];
if(!empty($_FILES['images']['tmp_name'])){
$length = 9;
$search = true; // allow the loop to begin
while($search == true) {
$rand_image_folder = substr(str_shuffle("0123456789"), 0, $length);
if (!file_exists('../post_images/'.$rand_image_folder)) {
$search = false;
}
}
mkdir("../post_images/".$rand_image_folder);
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['images']['name'][$key];
$file_size = $_FILES['images']['size'][$key];
$file_tmp = $_FILES['images']['tmp_name'][$key];
$file_type = $_FILES['images']['type'][$key];
$check_file_type = substr($file_type, 0, strrpos( $file_type, '/'));
if($check_file_type !== 'image'){
header('Location: ../members_area.php?posterror=1');
}
$extensions = array("jpeg","jpg","png","JPEG","JPG","PNG");
$format = trim(substr($file_type, strrpos($file_type, '/') + 1));
if(in_array($format,$extensions) === false){
header('Location: ../members_area.php?posterror=1');
} else {
move_uploaded_file($file_tmp,"../post_images/".$rand_image_folder."/".$file_name);
$file = "../post_images/".$rand_image_folder."/".$file_name;
$cut_name = substr($file, strpos($file, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = "../post_images/".$rand_image_folder."/thb_".$cut_name;
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = '350';
$max_height = '250';
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
}
}
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','$rand_image_folder','0','$post_public')");
} else {
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','','0','$post_public')");
}
header('Location: ../members_area.php?posterror=2');
}
I don't have any experience with PHP and images in general, but I have a need to resize all images into the square when they get uploaded.
Since I have multiple products and they have different pictures that comes in different sizes, I think that the best approach is to 'standardize' them during the upload by taking an image and 'fitting' it into the 800x800 white square while maintaining the aspect ratio (if longest size >800 then downsize, if longest size <800, then re-size).
My initial solution was created via JavaScript, where I tried to find the biggest picture and resize all other images according to it. Although, it is not very useful and can be faulty since if there is a delay in image load, images might not be loaded for JS to perform the operation, thus not showing images at all.
$product = getProductById($productid);
$filesArray = array();
if (isset($_GET['files']) && $productid > 0) {
$error = false;
$files = array();
$fileName = '';
$uploaddir = "../images/products/";
foreach ($_FILES as $file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$random_name = $widgets->randomFileName();
$randomFullFileName = $productid .'_'. $random_name . '.' . $ext;
//copy to location
//----------------
//HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
//----------------
if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
//save to database
$image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
if ($image_id > 0) {
echo 'Added new image';
} else {
echo 'Error, unable to add. <br> Please try again.';
}
} else {
echo 'Error, unable to add. <br> Please try again.';
}
}
}
Before: 600x300
After: 800x800 with white borders to fill-in the space
You can try this approach (tested). It will fit your images into an 800x800 square canvas while maintaining the aspect ratio of your images.
resize_image(): This function will maintain the aspect ratio of your image.
function resize_image($img,$maxwidth,$maxheight) {
//This function will return the specified dimension(width,height)
//dimension[0] - width
//dimension[1] - height
$dimension = array();
$imginfo = getimagesize($img);
$imgwidth = $imginfo[0];
$imgheight = $imginfo[1];
if($imgwidth > $maxwidth){
$ratio = $maxwidth/$imgwidth;
$newwidth = round($imgwidth*$ratio);
$newheight = round($imgheight*$ratio);
if($newheight > $maxheight){
$ratio = $maxheight/$newheight;
$dimension[] = round($newwidth*$ratio);
$dimension[] = round($newheight*$ratio);
return $dimension;
}else{
$dimension[] = $newwidth;
$dimension[] = $newheight;
return $dimension;
}
}elseif($imgheight > $maxheight){
$ratio = $maxheight/$imgheight;
$newwidth = round($imgwidth*$ratio);
$newheight = round($imgheight*$ratio);
if($newwidth > $maxwidth){
$ratio = $maxwidth/$newwidth;
$dimension[] = round($newwidth*$ratio);
$dimension[] = round($newheight*$ratio);
return $dimension;
}else{
$dimension[] = $newwidth;
$dimension[] = $newheight;
return $dimension;
}
}else{
$dimension[] = $imgwidth;
$dimension[] = $imgheight;
return $dimension;
}
}
And now comes your code,
$product = getProductById($productid);
$filesArray = array();
if (isset($_GET['files']) && $productid > 0) {
$error = false;
$files = array();
$fileName = '';
$uploaddir = "../images/products/";
foreach ($_FILES as $file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$random_name = $widgets->randomFileName();
$randomFullFileName = $productid .'_'. $random_name . '.' . $ext;
//copy to location
//----------------
//HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
// Create image from file
$image = null;
switch(strtolower($file['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($file['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($file['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($file['tmp_name']);
break;
default:
exit('Unsupported type: '.$file['type']);
}
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Get the new dimensions
$dimension = resize_image($file, 800, 800);
$new_width = $dimension[0];
$new_height = $dimension[1];
// 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);
// Catch and save the image
$status = false;
switch(strtolower($file['type']))
{
case 'image/jpeg':
$status = imagejpeg($new, $uploaddir . $randomFullFileName, 90);
break;
case 'image/png':
$status = imagepng($new, $uploaddir . $randomFullFileName, 0);
break;
case 'image/gif':
$status = imagegif($new, $uploaddir . $randomFullFileName);
break;
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
//save to database
if($status){
$image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
if ($image_id > 0) {
echo 'Added new image';
} else {
echo 'Error, unable to add. <br> Please try again.';
}
}else{
echo 'Error, unable to add. <br> Please try again.';
}
//----------------
//if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
// //save to database
// $image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
// if ($image_id > 0) {
// echo 'Added new image';
// } else {
// echo 'Error, unable to add. <br> Please try again.';
// }
//} else {
// echo 'Error, unable to add. <br> Please try again.';
//}
}
}
Original answer
How about imagine?
Insert this code before //save to database comment:
<?php
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box(800, 800);
$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine
->open($uploaddir . $randomFullFileName)
->thumbnail($size, $mode)
->save($uploaddir . $randomFullFileName);
New answer
As resize is not working like expected (thanks to #Pradeep Sanjaya), I would paste solution based on snippet from link:
/**
* Image resize
* #param string $input Full path to source image
* #param string $output Full path to result image
* #param int $width Width of result image
* #param int $height Height of result image
*/
function resizeImage($input, $output, $width, $height)
{
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box($width, $height);
$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$resizeimg = $imagine
->open($input)
->thumbnail($size, $mode);
$sizeR = $resizeimg->getSize();
$widthR = $sizeR->getWidth();
$heightR = $sizeR->getHeight();
$preserve = $imagine->create($size);
$startX = $startY = 0;
if ($widthR < $width) {
$startX = ($width - $widthR) / 2;
}
if ($heightR < $height) {
$startY = ($height - $heightR) / 2;
}
$preserve
->paste($resizeimg, new Imagine\Image\Point($startX, $startY))
->save($output);
}
And usage according to original question:
<?php
// placed after `save to database` comment
resizeImage(
$uploaddir . $randomFullFileNamem,
$uploaddir . $randomFullFileName,
800, 800
);
i am working on php function that would put watermark on image. I´ve got it working but i need to scale this watermark so the height of the watermark will be 1/3 of the original image. I can do that, but when i put it into my code it just doesnt work, because the parameter of imagecopymerge must be resource, which i dont know what means.
define('WATERMARK_OVERLAY_IMAGE', 'watermark.png');
define('WATERMARK_OVERLAY_OPACITY', 100);
define('WATERMARK_OUTPUT_QUALITY', 100);
function create_watermark($source_file_path, $output_file_path)
{
list($source_width, $source_height, $source_type) = getimagesize($source_file_path);
if ($source_type === NULL) {
return false;
}
switch ($source_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_file_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_file_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_file_path);
break;
default:
return false;
}
$overlay_gd_image = imagecreatefrompng(WATERMARK_OVERLAY_IMAGE);
$overlay_width = imagesx($overlay_gd_image);
$overlay_height = imagesy($overlay_gd_image);
//THIS PART IS WHAT SHOULD RESIZE THE WATERMARK
$source_width = imagesx($source_gd_image);
$source_height = imagesy($source_gd_image);
$percent = $source_height/3/$overlay_height;
// Get new sizes
$new_overlay_width = $overlay_width * $percent;
$new_overlay_height = $overlay_height * $percent;
// Load
$overlay_gd_image_resized = imagecreatetruecolor($new_overlay_width, $new_overlay_height);
// Resize
$overlay_gd_image_complet = imagecopyresized($overlay_gd_image_resized, $overlay_gd_image, 0, 0, 0, 0, $new_overlay_width, $new_overlay_height, $overlay_width, $overlay_height);
//ALIGN BOTTOM, RIGHT
if (isset($_POST['kde']) && $_POST['kde'] == 'pravo') {
imagecopymerge(
$source_gd_image,
$overlay_gd_image_complet,
$source_width - $new_overlay_width,
$source_height - $new_overlay_height,
0,
0,
$new_overlay_width,
$new_overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
if (isset($_POST['kde']) && $_POST['kde'] == 'levo') {
//ALIGN BOTTOM, LEFT
imagecopymerge(
$source_gd_image,
$overlay_gd_image,
0,
$source_height - $overlay_height,
0,
0,
$overlay_width,
$overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
imagejpeg($source_gd_image, $output_file_path, WATERMARK_OUTPUT_QUALITY);
imagedestroy($source_gd_image);
imagedestroy($overlay_gd_image);
imagedestroy($overlay_gd_image_resized);
}
/*
* Uploaded file processing function
*/
define('UPLOADED_IMAGE_DESTINATION', 'originals/');
define('PROCESSED_IMAGE_DESTINATION', 'images/');
function process_image_upload($Field)
{
$temp_file_path = $_FILES[$Field]['tmp_name'];
/*$temp_file_name = $_FILES[$Field]['name'];*/
$temp_file_name = md5(uniqid(rand(), true)) . '.jpg';
list(, , $temp_type) = getimagesize($temp_file_path);
if ($temp_type === NULL) {
return false;
}
switch ($temp_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_file_path = UPLOADED_IMAGE_DESTINATION . $temp_file_name;
$processed_file_path = PROCESSED_IMAGE_DESTINATION . preg_replace('/\\.[^\\.]+$/', '.jpg', $temp_file_name);
move_uploaded_file($temp_file_path, $uploaded_file_path);
$result = create_watermark($uploaded_file_path, $processed_file_path);
if ($result === false) {
return false;
} else {
return array($uploaded_file_path, $processed_file_path);
}
}
$result = process_image_upload('File1');
if ($result === false) {
echo '<br>An error occurred during file processing.';
} else {
/*echo '<br>Original image saved as ' . $result[0] . '';*/
echo '<br>Odkaz na obrazek je zde';
echo '<br><img src="' . $result[1] . '" width="500px">';
echo '<br><div class="fb-share-button" data-href="' . $result[1] . '" data-type="button"></div>';
}
I've been creating a HTML5 Drag & Drop image up-loader. All is good with the Javascript side of things however the PHP is driving me crazy!
I've been able to create a script that successfully places a image in a folder upon the drop of an image, however once it tries to create a thumb nail for the image and place the image link into the users db table it all goes to pot. I've sat here for hours on end, trying and trying to no avail, so i believe as it is now just about 3am GMT i should admit defeat and ask for a little help.
The JavaScript:
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
paramname:'pic',
maxfiles: 5,
maxfilesize: 200,
url: 'uploadCore.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files!');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 200mb.');
break;
default:
break;
}
},
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
image.attr('src',e.target.result);
};
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
Now for the PHP:
<?php
// db connection
include("db-info.php");
$link = mysql_connect($server, $user, $pass);
if(!mysql_select_db($database)) die(mysql_error());
include("loadsettings.inc.php");
//$upload_dir = 'pictures/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
if (isset($_SESSION["imagehost-user"]))
{
$session = true;
$username = $_SESSION["imagehost-user"];
$password = $_SESSION["imagehost-pass"];
$q = "SELECT id FROM `members` WHERE (username = '$username') and (password = '$password')";
if(!($result_set = mysql_query($q))) die(mysql_error());
$number = mysql_num_rows($result_set);
if (!$number) {
session_destroy();
$session = false;
}else {
$row = mysql_fetch_row($result_set);
$loggedId = $row[0];
}
}
$date = date("d-m-y");
$lastaccess = date("y-m-d");
$ip = $_SERVER['REMOTE_ADDR'];
$type = "public";
$pic = $_FILES['pic'];
$n = $pic;
$rndName = md5($n . date("d-m-y") . time()) . "." . get_extension($pic['name']);
$upload_dir = "pictures/" . $rndName;
move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
// issues starts here
$imagePath = $upload_dir;
$img = imagecreatefromunknown($imagePath);
$mainWidth = imagesx($img);
$mainHeight = imagesy($img);
$a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
$div = $a / 150;
$thumbWidth = intval($mainWidth / $div);
$thumbHeight = intval($mainHeight / $div);
$myThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($myThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainWidth, $mainHeight);
$thumbPath = "thumbnails/" . basename($imagePath);
imagejpeg($myThumb, $thumbPath);
$details = intval(filesize($imagePath) / 1024) . " kb (" . $mainWidth . " x " . $mainHeight . ")" ;
$id = md5($thumbPath . date("d-m-y") . time());
$q = "INSERT INTO `images`(id, userid, image, thumb, tags, details, date, access, type, ip)
VALUES('$id', '$loggedId', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'member-{$type}', '$ip')";
if(!($result_set = mysql_query($q))) die(mysql_error());*/
exit_status('File was uploaded successfuly!');
// to here
$result = mysql_query("SELECT id FROM `blockedip` WHERE ip = '$ip'");
$number = mysql_num_rows($result);
if ($number) die(""); // blocked IP message
function imagecreatefromunknown($path) {
$exten = get_extension($path);
switch ($exten) {
case "jpg":
$img = imagecreatefromjpeg($path);
break;
case "gif":
$img = imagecreatefromgif($path);
break;
case "png":
$img = imagecreatefrompng($path);
break;
}
return $img;
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
It seems you pass wrong path to the imagecreatefromunknown() function. You pass $imagePath that equals $upload_dir, but your image destination is $upload_dir.$pic['name']