I have an issue with uploading the same image twice, but in different sizes. What I thought I could do was having one file input, where I choose the image. In the upload php file, I have two variables:
$img = $_POST["file"];
$imgThumbnail = $_POST["file"];
I have then created a function to upload images to my webpage in php. I call the functions twice after each other, but the second time the function is called, I get the error "No such file or directory.." - the first image is uploaded correctly, but the second is not because of this error. What am I doing wrong, when the file is actually the same?
// First time, normal size img
uploadNewsIMG($imgFile, $pathToUpload, $img_author, $img_text, $img_tags, 950, "false");
// Second time, thumbnail size img - ERROR IS HERE "No such file or directory.. etc."
uploadNewsIMG($imgFileThumbnail, $pathToUpload, $img_author, $img_text, $img_tags, 400, "true");
When uploading the second image, this is the line that gives me the "No such.." error:
$fileName = $fileIMG['tmp_name']; // <- THIS IS THE VARIABLE "$imgFileThumbnail"
$image_size = getimagesize($fileName); // <- ERROR HERE
EDIT
This is the function uploadNewsIMG():
function uploadNewsIMG($fileIMG, $path, $author, $alt_text, $img_tags, $max_width, $thumbnail) {
global $con;
$realFileName = $fileIMG['name'];
$fileName = $fileIMG['tmp_name'];
$realFileName = str_replace("(", "", $realFileName);
$realFileName = str_replace(")", "", $realFileName);
$fileName = str_replace("(", "", $fileName);
$fileName = str_replace(")", "", $fileName);
$realFileName = strtolower($realFileName);
$now = strtotime("now");
if ($thumbnail != "true") {
$targetFilePath = "../../" . $path . $now . "-" . $realFileName;
$img_source_link = $path . $now . "-" . $realFileName;
} else {
$targetFilePath = "../../" . $path . "thumb-" . $now . "-" . $realFileName;
$img_source_link = $path . "thumb-" . $now . "-" . $realFileName;
}
$targetFilePath = str_replace(" ","", $targetFilePath);
$img_source_link = str_replace(" ","", $img_source_link);
// Resize billedet
$dimension = $max_width;
$image_size = getimagesize($fileName);
$mime = $image_size['mime'];
$width = $image_size[0];
$height = $image_size[1];
$ratio = $width / $height;
if ($ratio > 1) {
$new_width = $dimension;
$new_height = $dimension / $ratio;
} else {
$new_height = $dimension;
$new_width = $dimension * $ratio;
}
$src = imagecreatefromstring(file_get_contents($fileName));
$destination = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($destination, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if ($mime == "image/jpeg") {
imagejpeg($destination, $fileName, 100);
} else if ($mime == "image/png") {
imagepng($destination, $fileName, 9);
}
imagedestroy($src);
imagedestroy($destination);
if (move_uploaded_file($fileName, $targetFilePath)) {
}
}
The problem here is that once you call:
move_uploaded_file
The file is gone, and you can't access it on the second try because no such file exists anymore.
What I would recommend you to do instead is just copy the image instead of moving it. This way you will be able to run this function as many times as you like.
Here is the link for this function: PHP copy.
Related
I created a function to upload a cropped image from an html5 canvas which works fine. The only issue I have is that the imageinterlace function doesn't create
a progressive jpeg.
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
$tmp_name = $folder . $new_name;
move_uploaded_file($_FILES['image_file']['tmp_name'], $tmp_name);
if (file_exists($tmp_name) && filesize($tmp_name) > 0) {
$size = getimagesize($tmp_name);
switch($size[2]) {
case IMAGETYPE_JPEG:
$ext = '.jpg';
$v_image = #imagecreatefromjpeg($tmp_name);
break;
default:
return false;
}
imageinterlace($v_image, 1);
$destination_image = #imagecreatetruecolor( $request['width'], $request['height'] );
imagecopyresampled($destination_image, $v_image, 0, 0, (int)$request['x1'], (int)$request['y1'], (int)$request['width'], (int)$request['height'], (int)$request['w'], (int)$request['h']);
$result_name = $tmp_name . $ext;
imagejpeg($destination_image, $result_name, 90);
}
}
What am I doing wrong?
i'm a php newbie and still trying to get to grips with the language.
I need to crop the images i'm uploading into squares using php. Here is my current code to upload the images (which is working fine):
<?php
error_reporting(0);
$sUploadDirectory = 'uploads/';
$aFileTypesAllowed = array('image/jpeg', 'image/gif', 'image/png');
$aExtensionsAllowed = array('gif', 'png', 'jpg', 'jpeg');
$aJSExtensions = 'new Array("gif", "png", "jpg", "jpeg")';
$bImagesOnly = true;
$iMaxFileSize = 102400;
if(isset($_REQUEST['upload']) && $_REQUEST['upload'] == 'true') {
$bSuccess = true;
$sErrorMsg = 'Your image was successfully uploaded.';
if (array_search($_FILES['myFile']['type'], $aFileTypesAllowed) === false ||
!in_array(end(explode('.', strtolower($_FILES['myFile']['name']))), $aExtensionsAllowed)) {
$bSuccess = false;
$sErrorMsg = 'Invalid file format. Acceptable formats are: ' . implode(', ', $aFileTypesAllowed);
} else if ($bImagesOnly && !(getimagesize($_FILES['myFile']['tmp_name']))) {
$bSuccess = false;
$sErrorMsg = 'The image is invalid or corrupt. Please select another.';
} else if ($_FILES['myFile']['size'] > $iMaxFileSize) {
$bSuccess = false;
$sErrorMsg = 'The file size of your property photo must not exceed ' . ($iMaxFileSize / 1024) . 'Kb. Please try again.';
} else {
if (!#move_uploaded_file($_FILES['myFile']['tmp_name'], $sUploadDirectory . $_FILES['myFile']['name'])) {
$bSuccess = false;
$sErrorMsg = 'An unexpected error occurred while saving your uploaded photo. Please try again.';
}
}
print '<html>' .
'<head>' .
'<script type="text/javascript">' .
'parent.uploadResult(' . ($bSuccess ? 'true' : 'false') . ', \'' . $sErrorMsg . '\', \'' . $sUploadDirectory . $_FILES['myFile']['name'] . '\');' .
'</script>' .
'</head>' .
'<body></body>' .
'</html>';
die();
}
?>
I've tried adding this after the last argument checking the file size, it works on desktop, however doesn't on mobile when you use the 'take photo' option, which is an essential option in my design:
//*********************
//crop image into sqaure
//**********************
// Original image
$filename = $_FILES['myFile']['tmp_name'];
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = $current_width / 2 - 320;
$top = $current_height / 2 - 320;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 640;
$crop_height = 640;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width,
$current_height);
imagejpeg($canvas, $filename, 100);
//*********************
//crop image into sqaure
//**********************
I'm wondering if I have coded this poorly causing it not to work,
If any one could help i'd be very grateful! Thanks!
so this is the code that works on desktop but not on mobile, the first html entry above works on mobile and desktop.
<?php
error_reporting(0);
$sUploadDirectory = 'uploads/';
$aFileTypesAllowed = array('image/jpeg', 'image/gif', 'image/png');
$aExtensionsAllowed = array('gif', 'png', 'jpg', 'jpeg');
$aJSExtensions = 'new Array("gif", "png", "jpg", "jpeg")';
$bImagesOnly = true;
$iMaxFileSize = 4194304;
if(isset($_REQUEST['upload']) && $_REQUEST['upload'] == 'true') {
$temp = explode(".", $_FILES["myFile"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$bSuccess = true;
$sErrorMsg = 'Thanks! Your image was successfully uploaded.';
if (array_search($_FILES['myFile']['type'], $aFileTypesAllowed) === false ||
!in_array(end(explode('.', strtolower($_FILES['myFile']['name']))), $aExtensionsAllowed)) {
$bSuccess = false;
$sErrorMsg = 'Invalid file format. Acceptable formats are: ' . implode(', ', $aFileTypesAllowed);
} else if ($bImagesOnly && !(getimagesize($_FILES['myFile']['tmp_name']))) {
$bSuccess = false;
$sErrorMsg = 'The image is invalid or corrupt. Please select another.';
} else if ($_FILES['myFile']['size'] > $iMaxFileSize) {
$bSuccess = false;
$sErrorMsg = 'The file size of your property photo must not exceed ' . ($iMaxFileSize / 1024) . 'Kb. Please try again.';
} else {
$filename = $_FILES['myFile']['tmp_name'];
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = $current_width / 2 - ($current_width / 2);
$top = $current_height / 2 - ($current_width / 2);
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = $current_width;
$crop_height = $current_width;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
if (!#move_uploaded_file($_FILES['myFile']['tmp_name'], $sUploadDirectory . $newfilename)) {
$bSuccess = false;
$sErrorMsg = 'An unexpected error occurred while saving your uploaded photo. Please try again.';
}
}
print '<html>' .
'<head>' .
'<script type="text/javascript">' .
'parent.uploadResult(' . ($bSuccess ? 'true' : 'false') . ', \'' . $sErrorMsg . '\', \'' . $sUploadDirectory . $newfilename . '\');' .
'</script>' .
'</head>' .
'<body></body>' .
'</html>';
die();
}
?>
You can use the native PHP function imagecrop.
The following code will cut anything that is not a square (if the aspect ratio is greater or less than 1).
Of course, this is a little bit thrown together and could absolutely be a little bit more optimized, but it will do for now.
// Uploaded file temporary location
$fileTemp = $_FILES["myFile"]["tmp_name"];
// Validate the file extension.
$fileExt = strtolower(end(explode(".", $_FILES["myFile"]["name"])));
switch($fileExt){
case "jpg":
case "jpeg":
$image = imagecreatefromjpeg($fileTemp);
break;
case "png":
$image = imagecreatefrompng($fileTemp);
break;
case "gif":
$image = imagecreatefromgif($fileTemp);
break;
default:
$errorMessage = "Invalid file format. Acceptable formats are: " . implode(", ", $validFileTypes);
}
// Retrieve image resolution and aspect ratio.
list($width, $height) = getimagesize($fileTemp);
$aspectRatio = $width / $height;
// Crop the image based on the provided aspect ratio.
if($aspectRatio !== 1){
$portrait = $aspectRatio < 1;
// This will check if the image is portrait or landscape and crop it square accordingly.
$image = imagecrop($image, [
"x" => $portrait ? 0 : (($width - $height) / 2),
"y" => $portrait ? (($width - $height) / 2) : 0,
"width" => $portrait ? $width : $height,
"height" => $portrait ? $width : $height
]);
}
// Constrain max file size.
$maxFileSize = 102400;
if($_FILES["myFile"]["size"] >= $maxFileSize){
$errorMessage = "The file size of your property photo must not exceed " . ($maxFileSize / 1024) . "Kb. Please try again.";
}
// Send to CDN...
if(empty($errorMessage)){
}
I'm really new to joomla, I don't have idea what should I do to make it done. I just have this kind of code in administrator table, it refers to uploading files.
//Support for file field: cover
if(isset($_FILES['jform']['name']['cover'])):
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.file');
$file = $_FILES['jform'];
//Check if the server found any error.
$fileError = $file['error']['cover'];
$message = '';
if($fileError > 0 && $fileError != 4) {
switch ($fileError) :
case 1:
$message = JText::_( 'File size exceeds allowed by the server');
break;
case 2:
$message = JText::_( 'File size exceeds allowed by the html form');
break;
case 3:
$message = JText::_( 'Partial upload error');
break;
endswitch;
if($message != '') :
JError::raiseWarning(500,$message);
return false;
endif;
}
else if($fileError == 4){
if(isset($array['cover_hidden'])):;
$array['cover'] = $array['cover_hidden'];
endif;
}
else{
//Check for filesize
$fileSize = $file['size']['cover'];
if($fileSize > 10485760):
JError::raiseWarning(500, 'File bigger than 10MB' );
return false;
endif;
//Replace any special characters in the filename
$filename = explode('.',$file['name']['cover']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
//Add Timestamp MD5 to avoid overwriting
$filename = md5(time()) . '-' . implode('.',$filename);
$uploadPath = JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_comic'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.$filename;
$fileTemp = $file['tmp_name']['cover'];
if(!JFile::exists($uploadPath)):
if (!JFile::upload($fileTemp, $uploadPath)):
JError::raiseWarning(500,'Error moving file');
return false;
endif;
endif;
$array['cover'] = $filename;
}
endif;
I could upload the file (in this case, an image) from the codes above, but what I'll do next is creating a thumbnail for the uploaded image. I searched for the php codes through the internet but it doesn't seem to work since I can't synchronize it into joomla codes. Umm.. I've made a folder named thumbnail in images folder. So what should I do next?
I'll be so happy and grateful if any of you could help me with this. Thanks.
Well i can share technique I'm using, i hope it will help:
In table's method check after the all validation is done (at the end of the method, just before returning true) i add the following code:
$input = JFactory::getApplication()->input;
$files = $input->files->get('jform');
if (!is_null($files) && isset($files['image']))
$this->image = $this->storeImage($files['image']);
The i create a new method called storeImage() :
protected $_thumb = array('max_w' => 200, 'max_h' => 200);
private function storeImage($file) {
jimport('joomla.filesystem.file');
$filename = JFile::makeSafe($file['name']);
$imageSrc = $file['tmp_name'];
$extension = strtolower(JFile::getExt($filename));
// You can add custom images path here
$imagesPath = JPATH_ROOT . '/media/';
if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {
// Generate random filename
$noExt = rand(1000, 9999) . time() . rand(1000, 9999);
$newFilename = $noExt . '.' . $extension;
$imageDest = $imagesPath . $newFilename;
if (JFile::upload($imageSrc, $imageDest)) {
// Get image size
list($w, $h, $type) = GetImageSize($imageDest);
switch ($extension) {
case 'jpg':
case 'jpeg':
$srcRes = imagecreatefromjpeg($imageDest);
break;
case 'png':
$srcRes = imagecreatefrompng($imageDest);
break;
case 'gif':
$srcRes = imagecreatefromgif($imageDest);
break;
}
// Calculating thumb size
if($w > $h) {
$width_ratio = $this->_thumb['max_w'] / $w;
$new_width = $this->_thumb['max_w'];
$new_height = $h * $width_ratio;
} else {
$height_ratio = $this->_thumb['max_w'] / $h;
$new_width = $w * $height_ratio;
$new_height = $this->_thumb['max_w'];
}
$destRes = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($destRes, $srcRes, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Creating resized thumbnail
switch ($extension) {
case 'jpg':
case 'jpeg':
imagejpeg($destRes, $imagesPath . 'thumb_' . $newFilename, 100);
break;
case 'png':
imagepng($destRes, $imagesPath . 'thumb_' . $newFilename, 1);
break;
case 'gif':
imagegif($destRes, $imagesPath . 'thumb_' . $newFilename, 100);
break;
}
imagedestroy($destRes);
// Delete old image if it was set before
if (($this->image != "") && JFile::exists($imagesPath . $this->image)) {
JFile::delete($imagesPath . $this->image);
JFile::delete($imagesPath . 'thumb_' . $this->image);
}
return $newFilename;
}
}
}
}
return null;
}
This method returns uploaded file filename, which table stores in 'image' column. It creates two files, one original image and resized thumb with file prefix '_thumb'.
I hope it helps :)
I used Jimage : https://api.joomla.org/cms-3/classes/JImage.html
$JImage = new JImage($img_path);
$size_thumb = '150x150';
$JImage->createThumbs($size_thumb,1,$path.'/thumb');
Short, simple and efficient.
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}" );
This is the code that uploads users logo's I was wondering if anyone could help me.
I want to be able to allow users to upload .png and .gif files too.
Sorry if this is a simple fix but I am very new to php.
<?
//edit logo
function resize_image ($image) {
$imgsize = getimagesize($image);
//check for gallery type to determine thumbnail size
$size_x = 150;
$ratio = 150 / $imgsize[0];
$size_y = $imgsize[1] * $ratio;
$srcimage = ImageCreateFromjpeg ($image);
$newimage = ImageCreateTrueColor($size_x,$size_y);
//$newimage = imagecreate ($size_x, $size_y);
imagecopyresized ($newimage, $srcimage, 0, 0, 0, 0, $size_x, $size_y,
imagesx($srcimage), imagesy($srcimage));
return $newimage;
}
$myrepairer = new repairer;
//resize and upload image
$file = $_FILES['logo']['tmp_name'];
$file_name = $_FILES['logo']['name'];
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.jpg')) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.jpg');
unlink('logos/'.$_REQUEST['id'].'.jpg');
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.jpg');
}
$resultmessage = '<div align="center" class="GreenText">Logo Updated</div>';
You can just get the file extension and use it instead of '.jpg'.
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
So, it'll be something like:
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.'.$ext)) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.'.$ext);
unlink('logos/'.$_REQUEST['id'].'.'.$ext);
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.'.$ext);