Having Trouble Changing Avatar Location on my Wordpress site - php

So I am using a script made by someone else.
Wordpress site.
I want to change the default upload location:
mysite.com/wp-content/themes/theme_name/images/avatar/avatarnamehere20.jpg
To:
mysite.com/images/avatar/avatarnamehere20.jpg
Anyways, this is the working code for the first scenario:
Code that processes upload
if(isset($_FILES['image']))
$avatar = $_FILES['image'];
$save_to = "/images/avatar";
$logo_results = tgt_resize_image($avatar['tmp_name'] ,$save_to,150,150,$avatar['type'], get_the_author_meta('display_name', $user_ID));
if ($logo_results === false)
{
global $errors;
$errors .= __("Error: We can't upload your avatar", 'ad')."<br>";
}
else{
$avatar = get_user_meta($user_ID,'tgt_image',true);
if(file_exists(TEMPLATEPATH . $avatar) && $avatar != '/images/avatar.png')
unlink(TEMPLATEPATH . $avatar);
$avatar = $logo_results;
update_user_meta($user_ID,'tgt_image',$avatar);
}
Function tgt_resize_image
function tgt_resize_image($ipath, $tdir, $twidth, $theight, $image_type, $name_image){
try{
$simg = '';
//check image type
$type_arr = array('image/jpg', 'image/jpeg', 'image/pjpeg');
if (in_array($image_type, $type_arr))
{
$simg = imagecreatefromjpeg($ipath);
}
elseif($image_type == 'image/png'){
$simg = imagecreatefrompng($ipath);
}
elseif($image_type == 'image/gif'){
$simg = imagecreatefromgif($ipath);
}
else return false;
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg);
/* if ($twidth == 0) $twidth = $currwidth;
if ($theight == 0) $theight = $theight;*/
$dimg = imageCreateTrueColor($twidth, $theight); // Make New Image For Thumbnail
$name_image .= rand(1, 100);
$name_image = sanitize_file_name($name_image);
/*if($image_type == IMAGETYPE_GIF ) {
imagealphablending($dimg, false);
imagesavealpha($dimg,true);
$transparent = imagecolorallocatealpha($dimg, 255, 255, 255, 127);
imagefilledrectangle($dimg, 0, 0, $twidth, $theight, $transparent);
imagecolortransparent ( $dimg, $transparent);
} elseif( $image_type == IMAGETYPE_PNG ) {
// These parameters are required for handling PNG files.
imagealphablending($dimg, false);
imagesavealpha($dimg,true);
$transparent = imagecolorallocatealpha($dimg, 255, 255, 255, 127);
imagefilledrectangle($dimg, 0, 0, $twidth, $theight, $transparent);
}*/
imagecopyresampled ($dimg, $simg, 0, 0, 0, 0, $twidth, $theight, $currwidth, $currheight);
//imagecopyresized($dimg, $simg, 0, 0, 0, 0, $twidth, $theight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
// imagejpeg($dimg, TEMPLATEPATH . "$tdir/" . $name_image . '.jpg'); // Saving The Image
$link = $tdir . '/' . $name_image;
if (in_array($image_type, $type_arr))
{
imagejpeg($dimg, TEMPLATEPATH . "$tdir/" . $name_image . '.jpg');
$link .= '.jpg';
}
elseif($image_type == 'image/png'){
imagepng($dimg, TEMPLATEPATH . "$tdir/" . $name_image . '.png');
$link .= '.png';
}
elseif($image_type == 'image/gif'){
imagegif($dimg, TEMPLATEPATH . "$tdir/" . $name_image . '.gif');
$link .= '.gif';
}
}
catch (exception $e){
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
return false;
}
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
return $link;
// wp_attachment_is_image()
}
I had a few attempts at changing the code. I managed to get the mysql feild to update correctly but the file wouldn't upload at all. So the page tries to display the image but it does not exist.
This is what I got:
if(isset($_FILES['image']))
$avatar = $_FILES['image'];
//$save_to = "/images/avatar";
$save_to = site_url('/') . 'images/avatar';
$logo_results = tgt_resize_image($avatar['tmp_name'] ,$save_to,150,150,$avatar['type'], get_the_author_meta('display_name', $user_ID));
if ($logo_results === false)
{
global $errors;
$errors .= __("Error: We can't upload your avatar", 'ad')."<br>";
}
else{
$avatar = get_user_meta($user_ID,'tgt_image',true);
if(file_exists(site_url('/') . $avatar) && $avatar != '/images/avatar.png')
unlink(site_url('/') . $avatar);
$avatar = $logo_results;
update_user_meta($user_ID,'tgt_image',$avatar);
}
//wp_redirect( get_bloginfo('url').'/?author='.$current_user->ID );
wp_redirect(get_author_posts_url($user_ID));
exit;
In the tgt_resize_image function, I changed the TEMPLATEPATH to the site_url('/') but that did not work.
Any help is appreciated! I will reward the person who does help me cause this is frustrating!
Let me know if you need more info or code from anywhere.
Thanks again!

Okay I found the answer!
In the function: tgt_resize_image
imagejpeg, imagepng and imagegif were saving the image file.
TEMPLATEPATH was pointing to the WP template location.
Using site_url() would not work as it would now be pointing to the web location (mysite.com).
I had to replace TEMPLATEPATH with $_SERVER['DOCUMENT_ROOT'] and it ended up working fine.
Good luck!

Related

Cannot upload two of the same image files

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.

Why is imageinterlace not working?

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?

Using php to crop an image into a square when uploading to a server

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)){
}

Creating thumbnail from an uploaded image in Joomla 2.5

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.

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}" );

Categories