I have a script;
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// make the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $imagesDir . $randName . '.' . $ext;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
which am using to upload images but I would like to add a script to resize the image to a specific size before it's uploaded. How do I do that???
EDIT: I have updated this to include your script elements. I'm starting from the point where you obtain your filename.
Here is a very quick, simple script to do it:
$result = move_uploaded_file($tmpName, $filePath);
$orig_image = imagecreatefromjpeg($filePath);
$image_info = getimagesize($filePath);
$width_orig = $image_info[0]; // current width as found in image file
$height_orig = $image_info[1]; // current height as found in image file
$width = 1024; // new image width
$height = 768; // new image height
$destination_image = imagecreatetruecolor($width, $height);
imagecopyresampled($destination_image, $orig_image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// This will just copy the new image over the original at the same filePath.
imagejpeg($destination_image, $filePath, 100);
Well, you can't change the size of it before it's uploaded, but you can use the GD Library to change the size of it after it's on the server. Check out GD and Image Functions listing for all of the related functions for dealing with images.
There is also this tutorial that will show you a custom class for doing a resize, but unless you need the whole think you can focus on the function resize to see how it's done
Related
i read some topics similar to this but couldn't understand
i just want to upload images resize them then add watermark and finally save
this is my code :
$targetDir = "picem/";
$watermarkImagePath = 'icon/stamp.png';
if(!empty($_FILES["file"]["name"])){
// File upload path
foreach ($_FILES['file']['name'] as $name => $value)
{
$fileName = explode(".", $_FILES['file']['name'][$name]);
$new_name = md5(rand()) . '.' . $fileName[1];
$targetFilePath = $targetDir . $new_name;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg');
if(in_array($fileName[1], $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["file"]["tmp_name"][$name], $targetFilePath)){
// Load the stamp and the photo to apply the watermark to
$watermarkImg = imagecreatefrompng($watermarkImagePath);
switch($fileType){
case 'jpg':
$im = imagecreatefromjpeg($targetFilePath);
break;
case 'jpeg':
$im = imagecreatefromjpeg($targetFilePath);
break;
case 'png':
$im = imagecreatefrompng($targetFilePath);
break;
default:
$im = imagecreatefromjpeg($targetFilePath);
}
// Set the margins for the watermark
$marge_right = 10;
$marge_bottom = 10;
// Get the height/width of the watermark image
$sx = imagesx($watermarkImg);
$sy = imagesy($watermarkImg);
// Copy the watermark image onto our photo using the margin offsets and
// the photo width to calculate the positioning of the watermark.
imagecopy($im, $watermarkImg, (imagesx($im) - $sx - $marge_right)/2, (imagesy($im) - $sy
- $marge_bottom)/2, 0, 0, imagesx($watermarkImg), imagesy($watermarkImg));
// Save image and free memory
imagepng($im, $targetFilePath);
imagedestroy($im);
i would really appreciate if someone help me to make the result of
imagepng($im, $targetFilePath);
small image because right now i get some files with the size of 10MB
I have a script that upload an image file to rackspace container, what I want to happen after that is
Create a copy of that image file.
Put the file into memory and resize the image.
Upload the file to the rackspace container with new file name.
Trouble is I'm not sure how to take the resampled image in memory and upload to rackspace container. Here is code.
$objectStoreService = $client->objectStoreService(null, 'IAD');
$container = $objectStoreService->getContainer(IMAGE_CONTAINER_NAME);
$fileData = fopen($_FILES['file-0']['tmp_name'], 'r');
$uniqid = uniqid();
$new_file_path = $uniqid."/".$_FILES['file-0']['name'];
$sm_file_path = $uniqid . "/" . 'sm_' .$_FILES['file-0']['name'];
// Upload filepath to database
$user->upload_profile_pic($new_file_path, $sm_file_path);
$result = $container->uploadObject($new_file_path, $fileData);
$new_file_path = IMAGE_CONTAINER_LINK."/".$new_file_path;
// Make Thumbnail of original image
$percent = 0.5; // percentage of resize
// Image to be changed.
$original_image = imagecreatefromjpeg($new_file_path);
list($width, $height) = getimagesize($new_file_path);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Temporary blank image in memory of height/width
$tmp_image = imagecreatetruecolor($new_width, $new_height);
// Copies the source image and copies into it the blank image and resamples it.
imagecopyresampled($tmp_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save the image in memory
imagejpeg($tmp_image, NULL, 100);
// read the file
// Not sure how to put image in memory to rackspace cloud.
$fileData = fopen($tmp_image, 'r');
$tmp_image = imagecreatefromstring(file_get_contents($new_file_path));
$fileData = fopen($tmp_image, 'r');
$result = $container->uploadObject($sm_file_path, $fileData);
$response = array('image_path' => $new_file_path);
header('HTTP/1.1 201 Created');
echo json_encode($response);
I am trying to upload some images using import.csv file. The images need to be resized before uploading. I am using this code for uploading but it is returning a black image of the given size.
<?php
error_reporting(E_ALL);
include('config.php');
include('inc/header.php');
define('CSV_PATH', '');
$csv_file = CSV_PATH . "importImage.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$url = $insert_csv['url'] = $csv_array[0];
$image = $insert_csv['image'] = $csv_array[1];
$raw = file_get_contents($url . $image);
/*RESIZE USING GD*/
/*
* PHP GD
* resize an image using GD library
*/
// File and new size
//the original image has 800x600
$filename = $raw;
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = 200;
$newheight = 200;
// Load
$thumb = imagecreate($newwidth, $newheight);
$source = imagecreate($filename);
// Resize
$imgnew = imagecopyresampled($thumb, $source, 0, 0, 0, 0, newwidth, $newheight, $width, $height);
imagejpeg($thumb, 'Mypath' . time() . '.jpg'); // save resized image to
//Output and free memory
imagedestroy($thumb);
$i++;
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
The following script will easily allow you to resize images using PHP and the GD library.
https://github.com/nomisoft/White-Hat-Classes/tree/master/Simple-Image
First, check that the $url.$image is a real image.
Second, getimagesize requires an image path, not the image
I'm pretty sure you want this: http://runnable.com/UnF-tFdudNt1AABt/how-to-resize-an-image-using-gd-library-for-php
Hello I was looking at creating a thumbnail along with my main image. I would like it to be stored in a different folder than the original and be a maximum height of 400px. I have had a search around but it all seems too complex. I was looking for something fairly simple. I am new to the file uploading stuff. Below is the code I currently have.
// Configuration
$allowed_filetypes = array('.jpg', '.JPG', '.bmp', '.png', '.gif');
$max_filesize = 100000000;
$upload_path = 'artimages/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
// Random Number
$randomnumber = rand(1, 1000000);
$filename = $randomnumber.$filename;
// File Size
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// File Type
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Check CHMOD 777
if(!is_writable($upload_path))
die('Fail');
// Upload File
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Success';
else
echo 'Fail';
The code below will require PHP-GD
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// 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}{$fname}" );
}
You can do something like that:
$tmp_path = /*the temp path of your picture*/;
$imagePath = /*the path of you uploaded picture*/;
$Thumbnail = /*the path of your thumbnail folder*/;
move_uploaded_file($tmp_path, $imagePath);
copy($imagePath, $thumbnailPath);
So you will upload your image and just after that you will copy it in another location.
I'm having a hard time to make my web-application work properly. I have been trying to make my avatar not feel pushed and make it resize automatically when uploaded. I'm not the best with PHP hence why I can't do this on my own. I would appreciate if someone could help me out. That's the code of the file that is the avatar.
Best regards!
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
You'll require to store Uploaded Picture on your webserver
For that:
You'll Require:
move_uploaded_file()
and for resizing purpose you can use:
imagecopyresampled()
as follows:
function resizeIMG($o_img // original image
, $target_image // Resized New Image
, $newWidth, $newHeight){
// Get Original Dimensions as follows:
$original_width=imagesx($o_image); //Returns width of image
$original_height=imagesy($o_image); //Returns height of image
$tmp = imagecreatetruecolor($newWidth, $newHeight); // Create New temp. image with new dimensions
imagecopyresampled($tmp_img, $o_img, 0, 0, 0, 0, $newWidth, $newHeight, $original_width, $original_height); // Resize original image to temporary Image
imagejpeg($tmp, $target_image, $quality); // Copy temp Image to Target File for JPG images
imagedestroy($tmp); // Destroy Temporary Image.
/* Use
imagepng() instead of imagejpeg() for PNG images
imagegif() instead of imagejpeg() for GIF images
*/
}
For all these functions mentioned you'll need to enable gd_drivers for your php. By simply removing ; before line extension=php_gd2.dll if you're using windows or See this for others.
Or you can Use image_magick for php.
also do have a look at: Resize images in PHP without using third-party libraries?
hope it helps.. cheers :).