I used the following code to upload an image to a folder. My folder name is ADS. Please help me to upload that image to my ADS directory.
root - localhost/dc/upload.php
(the code is in this location)
The image should be added to the folder in location localhost/dc/ADS
if (isset($_POST["submit"])) {
if (is_array($_FILES)) {
$file = $_FILES['myImage']['tmp_name'];
$source_properties = getimagesize($file);
$image_type = $source_properties[2];
if ($image_type == IMAGETYPE_JPEG ) {
$image_resource_id = imagecreatefromjpeg($file);
echo $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
echo imagejpeg($target_layer,$_FILES['myImage']['name']);
} elseif ($image_type == IMAGETYPE_GIF ) {
$image_resource_id = imagecreatefromgif($file);
echo$target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
echo imagegif($target_layer,$_FILES['myImage']['name'] );
} elseif ($image_type == IMAGETYPE_PNG ) {
$image_resource_id = imagecreatefrompng($file);
echo$target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
echo imagepng($target_layer,$_FILES['myImage']['name']);
}
}
}
function fn_resize($image_resource_id,$width,$height)
{
$target_width =540;
$target_height =400;
$target_layer=imagecreatetruecolor($target_width,$target_height);
imagecopyresampled($target_layer,$image_resource_id,0,0,0,0,$target_width,$target_height, $width,$height);
return $target_layer;
}
When I use this code the image is displayed as in the Image1. I need it be like in Image2 without any change to the image and also I need to have a text or image watermark on the image as in the Image3.
The PHP functions imagepng imagegif and imagejpeg all have an argument to pass a file name to. I refactored your code to show this.
<?php
if (isset($_POST["submit"])) {
if (is_array($_FILES)) {
$file = $_FILES['myImage']['tmp_name'];
$source_properties = getimagesize($file);
$image_type = $source_properties[2];
if ($image_type == IMAGETYPE_JPEG) {
$image_resource_id = imagecreatefromjpeg($file);
echo $target_layer = fn_resize($image_resource_id, $source_properties[0], $source_properties[1]);
imagejpeg($target_layer, "localhost/dc/ADS/" . $_FILES['myImage']['name']);
}
elseif($image_type == IMAGETYPE_GIF) {
$image_resource_id = imagecreatefromgif($file);
echo$target_layer = fn_resize($image_resource_id, $source_properties[0], $source_properties[1]);
imagegif($target_layer, "localhost/dc/ADS/" . $_FILES['myImage']['name']);
}
elseif($image_type == IMAGETYPE_PNG) {
$image_resource_id = imagecreatefrompng($file);
echo$target_layer = fn_resize($image_resource_id, $source_properties[0], $source_properties[1]);
imagepng($target_layer, "localhost/dc/ADS/" . $_FILES['myImage']['name']);
}
}
}
function fn_resize($image_resource_id, $width, $height) {
$target_width = 540;
$target_height = 400;
$target_layer = imagecreatetruecolor($target_width, $target_height);
imagecopyresampled($target_layer, $image_resource_id, 0, 0, 0, 0, $target_width, $target_height, $width, $height);
return $target_layer;
}
Related
I have a code:
<?php
$size = 2000000;
$types = array('image/png', 'image/jpeg');
if(isset($_POST['go'])){
$newName = $id . '.' . $type;
$directory = 'img/avatars/'; //path to folder with images
$picture = $directory . basename($newName);
if (!in_array($_FILES['picture']['type'], $types)) {
die('Wrong type of file. Try another');
} elseif ($_FILES['picture']['size'] > $size) {
die('File is too big. Try another');
} elseif (move_uploaded_file($_FILES['picture']['tmp_name'], $picture)) {
echo "Image was downloaded!";
}
$new_width = 66; //necessary width
$size = getimagesize($picture);
$width = $size[0];
$height = $size[1];
if ($type == 'png') {
$src=ImageCreateFromPng($picture);
}
if ($type == 'jpeg' || $type == 'jpg') {
$src=ImageCreateFromJPEG($picture);
}
$coefficient = $width/$new_width;
$new_height = ceil($height/$coefficient);
$empty_picture = ImageCreateTrueColor($new_width, $new_height);
ImageCopyResampled($empty_picture, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if ($type == 'png') {
ImagePNG($empty_picture, $picture, -1);
}
if ($type == 'jpeg') {
ImageJPEG($empty_picture, $picture, -1);
}
imagedestroy($src);
}
?>
It returns an error:
imagecreatefrompng(): 'img/avatars/6.png' is not a valid PNG file in
W:\domains\mysite\settings.php
I checked is it png image:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $picture); // image/png
finfo_close($finfo);
And it returns me: image/png (it is).
So I do not know what is wrong with this code. Would be grateful for any help!
I am working on a project which multiple pages validation. My main issue is with the upload part of the code. What i am doing is when a user upload his images; i save them in a tempfolder then once form filled complete, i move the images from temp to mainfolder but before i want to resize the images before saving them in mainfolder.
How can i achieve that ?
I have tried myself but could not get it right.here is my code
i got this error : getimagesize(174349.jpg): failed to open stream: No such file or directory
imageuploaded.php
<?php
define('MAX_FILE_SIZE', 952070);
define('UPLOAD_DIR_TEMP', BASE_URI.'html/temp/');
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg','image/png');
if (array_key_exists('upload', $_POST)) {
foreach ($_FILES['image']['name'] as $number => $file) {
// replace any spaces in the filename with underscores
$file = str_replace(' ','_',$file);
$fileNom = pathinfo($_FILES['image']["name"][$number], PATHINFO_FILENAME);
$ext = pathinfo($_FILES['image']["name"][$number],PATHINFO_EXTENSION);
//$soruceimg = $_FILES['image']['tmp_name'];
//echo $file;
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;
// check that file is within the permitted size
if ($_FILES['image']['size'][$number] > 0 || $_FILES['image']['size'][$number] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image']['type'][$number]) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['image']['error'][$number]) {
case 0:
// get the date and time
ini_set('date.timezone', 'Africa/Abidjan');
$now = date('Y-m-d-His');
//$Nfilename = basename(substr($file,0,6).$now).".".$ext ." ";
$successes = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR_TEMP.$file);
if ($successes) {
$_SESSION['imgname']= $_FILES['image']['name'];
header('Location: test.php');
//echo $file;
}
else {
$resultfile[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$resultfile[] = "Error uploading $file. Please try again.";
default:
$resultfile[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['image']['error'][$number] == 4) {
$errNofile[] = 1;
}
else {
$resultfile[] = "$file cannot be uploaded. Maximum size: $max.Acceptable file types: gif, jpg, png.";
}
}
}
imageresize.php
$source = BASE_URI.'html/temp/';
define('THUMBS_DIR', BASE_URI.'html/products/thumbs/');
define('MAX_WIDTH', 200);
define('MAX_HEIGHT', 200);
define('UPLOAD_DIR', BASE_URI.'html/products/');
ini_set('date.timezone', 'Africa/Abidjan');
$now = date('Y-m-d-His');
if (isset($_SESSION['imgname']) && is_array($_SESSION['imgname']) ) {
foreach ($_SESSION['imgname'] as $files) {
echo $files;
$img = str_replace(" ", "_", $files);
$ext = pathinfo($img,PATHINFO_EXTENSION);
if (file_exists($source.$img)) {
$ext = pathinfo($img,PATHINFO_EXTENSION);
// strip the extension off the image filename
$imagetypes = array('/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/');
$name = preg_replace($imagetypes, '', basename(substr($img,0,6).$now));
list($width, $height, $type) = getimagesize($img);
if ($width != $height) {
echo "file width and height must be same";
break;
}
elseif ( $width < 300 && $height < 300) {
echo "File must be at least 400 x 400";
break;
}
else{
$ratio = 1;
$ratio = MAX_WIDTH/$width;
}
$Nfilename = $name.'.'.$ext;
$moved = rename($source.$img, UPLOAD_DIR.$Nfilename);
if (!$moved) {
echo "Problem moving file".$img;
}
else{
// create an image resource for the original
switch($type) {
case 1:
$source = # imagecreatefromgif($original);
if (!$source) {
$result = 'Cannot process GIF files. Please use JPEG or PNG.';
}
break;
case 2:
$source = imagecreatefromjpeg($original);
break;
case 3:
$source = imagecreatefrompng($original);
break;
default:
$source = NULL;
$result = 'Cannot identify file type.';
}
// make sure the image resource is OK
if (!$source) {
$result = 'Problem copying original';
}
else {
// calculate the dimensions of the thumbnail
$thumb_width = round($width * $ratio);
$thumb_height = round($height * $ratio);
// create an image resource for the thumbnail
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
// create the resized copy
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
// save the resized copy
switch($type) {
case 1:
if (function_exists('imagegif')) {
$success = imagegif($thumb, THUMBS_DIR.$name.'_thb.gif');
$thumb_name = $name.'_thb.gif';
}
else {
$success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 50);
$thumb_name = $name.'_thb.jpg';
}
break;
case 2:
$success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 100);
$thumb_name = $name.'_thb.jpg';
break;
case 3:
$success = imagepng($thumb, THUMBS_DIR.$name.'_thb.png');
$thumb_name = $name.'_thb.png';
}
if ($success) {
$result = "$thumb_name created";
}
else {
$result = 'Problem creating thumbnail';
}
if ($success) {
echo $thumb_name;
}
// remove the image resources from memory
imagedestroy($source);
imagedestroy($thumb);
}
}
}
else{
echo "No file exist";
}
}
}
Convert the image to bitmap first and use bitmap compression with defined ratio to compress the size.
you can compress the image by declaring specific height and width also.
I had this code before, very easy to use, it works for me
class SimpleImage {
var $image; var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); }
elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); }
elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); }
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); }
elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); }
elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); }
if( $permissions != null) { chmod($filename,$permissions); }
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); }
elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); }
elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); }
}
function getWidth() { return imagesx($this->image); }
function getHeight() { return imagesy($this->image); }
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio; $this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio; $this->resize($width,$height);
}
function scale($scale) { $width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100; $this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image; }
}
Use it as prev image, and save new image
$imageRes = new SimpleImage();
$imageRes->load($_SERVER['DOCUMENT_ROOT'] . '/upload/' . $image . '.jpg');//prev image
$imageRes->resizeToWidth(120);
$imageRes->save($_SERVER['DOCUMENT_ROOT'] . '/upload/' . $image . '.jpg');//new image
I have this code, I want to resize the picture, it manage to do the first one which 100x100 but not the others. I don't see why it doesn't work, it doesn't have any error. I'm a php newbie, doesn't really know what went wrong, but as you can see as the code does works for the 1st one but why doesn't work for the others?
<?php
function thumbnail($image, $width, $height) {
$image_properties = getimagesize($image);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$image_ratio = $image_width / $image_height;
$type = $image_properties["mime"];
if(!$width && !$height) {
$width = $image_width;
$height = $image_height;
}
if(!$width) {
$width = round($height * $image_ratio);
}
if(!$height) {
$height = round($width / $image_ratio);
}
if($type == "image/jpeg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($image);
} elseif($type == "image/png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($image);
} elseif($type == "image/gif") {
header('Content-type: image/gif');
$thumb = imagecreatefromgif($image);
}
else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
imagecopyresampled($temp_image, $thumb, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
$thumbnail = imagecreatetruecolor($width, $height);
imagecopyresampled($thumbnail, $temp_image, 0, 0, 0, 0, $width, $height, $width, $height);
if($type == "image/jpeg") {
imagejpeg($thumbnail);
}
elseif($type == "image/jpeg") {
imagepng($thumbnail);
}
elseif($type == "image/gif") {
imagegif($thumbnail);
}
imagedestroy($temp_image);
imagedestroy($thumbnail);
}
$pic_size = array();
// Adjust size
$pic_size['height'][0] = 100;
$pic_size['width'][0] = 100;
$pic_size['height'][1] = 200;
$pic_size['width'][1] = 200;
$pic_size['height'][2] = 300;
$pic_size['width'][2] = 300;
$pic_size['height'][3] = 400;
$pic_size['width'][3] = 400;
$pic_size['height'][4] = 500;
$pic_size['width'][4] = 500;
$total_pic_size= count($pic_size['height']);
$x = 0;
foreach(array_keys($pic_size['height']) as $x) {
thumbnail($_GET["img"], $pic_size['width'][$x], $pic_size['height'][$x]);
echo '<img src="index.php?w='.$pic_size['width'][$x].'&h='.$pic_size['height'][$x].'&img='.$_GET["img"].'" />';
$x++;
}
?>
You iterate only two times, because
$total_pic_size= count($pic_size);// is 2
Change that to:
$total_pic_size= count($pic_size['height']);
Or use foreach:
foreach(array_keys($pic_size['height']) as $x)
And don't use COUNT_RECURSIVE here, it will return wrong number again, counting in the width and height keys.
Also thumbnail function has header call in it, which cannot be called after echo, which in your case, is called after echo, in your loop. You should see the warning saying "Headers already sent".
You can save the image to file and echo image with file path as a source. Remove the header calls and let your thumbnail function save it and return the file name, for example:
imagejpeg($thumbnail, $filename);
return $filename;
and use the output as src of the echoed image.
Your $total_pic_size is always 2.
$total_pic_size = count( $pic_size['width'] );
This will give you the correct number of items and the loop should run not only once.
You should also change the loop-condition:
while ($x <= $total_pic_size) {
#Update 1
You can try something like this:
// ...
$pic_sizes[0]['height'] = 100;
$pic_sizes[0]['width'] = 100;
$pic_sizes[1]['height'] = 200;
$pic_sizes[1]['width'] = 200;
$pic_sizes[2]['height'] = 300;
$pic_sizes[2]['width'] = 300;
$pic_sizes[3]['height'] = 400;
$pic_sizes[3]['width'] = 400;
$pic_sizes[4]['height'] = 500;
$pic_sizes[4]['width'] = 500;
$img = $_GET["img"];
foreach ($pic_sizes as $pic_size) {
thumbnail($img, $pic_size['width'], $pic_size['height']);
echo '<img src="index.php?w='.$pic_size['width'].'&h='.$pic_size['height'].'&img='.$img.'" />';
}
#Update 2:
You already accepted another answere, but maybe this is also helpful for you. i found some more errors and logic-problems in your code... the code below works (without saving the thumbs).
<?php
function thumbnail($image, $width, $height) {
$image_properties = getimagesize($image);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$image_ratio = $image_width / $image_height;
$type = $image_properties["mime"];
if(!$width && !$height) {
$width = $image_width;
$height = $image_height;
}
if(!$width) {
$width = round($height * $image_ratio);
}
if(!$height) {
$height = round($width / $image_ratio);
}
if($type == "image/jpeg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($image);
} elseif($type == "image/png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($image);
} elseif($type == "image/gif") {
header('Content-type: image/gif');
$thumb = imagecreatefromgif($image);
}
else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
imagecopyresampled($temp_image, $thumb, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
$thumbnail = imagecreatetruecolor($width, $height);
imagecopyresampled($thumbnail, $temp_image, 0, 0, 0, 0, $width, $height, $width, $height);
if($type == "image/jpeg") {
imagejpeg($thumbnail);
}
elseif($type == "image/png") {
imagepng($thumbnail);
}
elseif($type == "image/gif") {
imagegif($thumbnail);
}
imagedestroy($temp_image);
imagedestroy($thumbnail);
}
$img = $_GET["img"];
$gen = #$_GET["gen"];
$w = #$_GET["w"];
$h = #$_GET["h"];
if ( !$gen ) {
$pic_sizes = array();
// Adjust size
$pic_sizes[0]['height'] = 100;
$pic_sizes[0]['width'] = 100;
$pic_sizes[1]['height'] = 200;
$pic_sizes[1]['width'] = 200;
$pic_sizes[2]['height'] = 300;
$pic_sizes[2]['width'] = 300;
$pic_sizes[3]['height'] = 400;
$pic_sizes[3]['width'] = 400;
$pic_sizes[4]['height'] = 500;
$pic_sizes[4]['width'] = 500;
foreach ($pic_sizes as $pic_size) {
echo '<img src="'.$_SERVER['PHP_SELF'].'?w='.$pic_size['width'].'&h='.$pic_size['height'].'&img='.$img.'&gen=1" />';
}
} else {
thumbnail($img, $w, $h);
}
I am using the following code which re-sizes an image to the height that I want.
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
However in my old code I was saving the image on the same server - I have since learned a little about s3 from Amazon and would like to upload the resized images to that.
Currently if I want to upload an image to S3 I do the following
function uploadmedia(){
include('s3upload/image_check.php');
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$tmp = $_FILES['file']['tmp_name'];
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size < 1048576)
{
include('s3upload/s3_config.php');
//Rename image name.
$savename = base64_encode($name);
$actual_image_name = $savename.time().".".$ext;
if($s3->putObjectFile($tmp, $bucket , $actual_image_name, S3::ACL_PUBLIC_READ) )
{
$s3file='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
}
else
$msg = "S3 Upload Fail.";
}
else
$msg = "Image size Max 1 MB";
}
else
{
$msg = "Invalid file, please upload image file.";
}
}
Now going back to the first code I would normally save the image via this method
$image = new SimpleImage();
$image->load($targetFile);
$image->resizeToHeight(80);
$image->save(rtrim($targetPath,'/') . '/' . md5($_FILES['Filedata']['name']) . '-x-h80.' . $ext);
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
I was wondering if anyone knows of the way to instead of saving the image to the old file system, instead re-size the image to 80x80 and upload it to s3
Thank you.
Here is the full image resize script
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
// Define a destination
$targetFolder = '/uploads'; // Relative to the root
if (!empty($_FILES["Filedata"])) {
$name = $_FILES['Filedata']['name'];
$ext = end(explode(".", $name));
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . md5($_FILES['Filedata']['name']) . '.' . $ext;
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$link = array();
$link['large'] = "http://www.ipetfindr.com/petuploads/". md5($_FILES['Filedata']['name']) . '.' . $ext;
$link['small'] = "http://www.ipetfindr.com/petuploads/". md5($_FILES['Filedata']['name']) . '-x-h80.' . $ext;
move_uploaded_file($tempFile,$targetFile);
$image = new SimpleImage();
$image->load($targetFile);
$image->resizeToHeight(80);
$image->save(rtrim($targetPath,'/') . '/' . md5($_FILES['Filedata']['name']) . '-x-h80.' . $ext);
echo '1';
}
else
{print "did not work";}
You have the solution already with you.
$image = new SimpleImage();
$image->load($targetFile);
$image->resize(80,80);
$image->save($url);
That above part resizes the target file to 80X80
$s3->putObjectFile($targetFile, $bucket , $name_in_s3, S3::ACL_PUBLIC_READ);
The above part saves the targetfile to s3 bucket
unlink("/path/to/targetFile");
The above part to delete the targetFile on your machine, once you have uploaded to s3. If you forget this part, your system will be filled with resized images.
This question already has answers here:
php - resize and save an image? [duplicate]
(3 answers)
Closed 9 years ago.
I'm resizing and saving multiple images from a URL and was wondering how I can compress these images more as the images that are saving in the 640x320 folder are 400kb which is too big and was wondering how I can compress these images more, thanks in advance for any advice!
PHP RESIZE AND SIZE HANDLER
include("../includes/picture-resize.php");
$image = $_POST['thumbnail'];
$slug = $_POST['slug'];
$images = $_POST['screenshots'];
$list = explode(",", $images);
$listlength = count($list);
$i = 0;
$image = $_POST['thumbnail'];
$path = parse_url($image, PHP_URL_PATH);
$filename = $slug.'-'.$i;
$extension = pathinfo($path, PATHINFO_EXTENSION);
$file = $filename.'.'.$extension;
file_put_contents('../tmp/' . $file, file_get_contents($image));
$picture = new pic_resize();
$picture->load('../tmp/'.$file);
$picture->resizeToWidth(125);
mkdir('../images/125x125/'.$slug);
$picture->save('../images/125x125/'.$slug.'/'.$file, $picture->image_type);
unlink('../tmp/'.$file);
$thumbnail = $file;
$new_list = array();
mkdir('../images/640x320/'.$slug);
mkdir('../images/310x205/'.$slug);
while($listlength > $i) {
$path = parse_url($list[$i], PHP_URL_PATH);
$filename = $slug.'-'.$i;
$extension = pathinfo($path, PATHINFO_EXTENSION);
$file = $filename.'.'.$extension;
file_put_contents('../tmp/' . $file, file_get_contents($list[$i]));
$picture = new pic_resize();
$picture->load('../tmp/'.$file);
$picture->resizeToWidth(640);
$picture->save('../images/640x320/'.$slug.'/'.$file, $picture->image_type);
$picture->resizeToWidth(310);
$picture->save('../images/310x205/'.$slug.'/'.$file, $picture->image_type);
unlink('../tmp/'.$file);
array_push($new_list, $file);
$i++;
}
PHP RESIZE CLASS
class pic_resize{
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename,9,PNG_FILTER_PAETH);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
3rd parameter:
JPEG Quality : Compression level: from 0 (most compression) to 100 (least compression).
http://www.php.net/manual/en/function.imagejpeg.php
PNG Quality : Compression level: from 0 (no compression) to 9.
http://www.php.net/manual/en/function.imagepng.php
Note that that the quality/size settings are pretty much different/backwards between jpeg and png