I would like to resize, rename and upload an image with PHP.
So my working script is the following:
$file_name = $_FILES['HOT_Logo']['name'];
$file_tmp_name = $_FILES['HOT_Logo']['tmp_name'];
$file_target = '../../images/hotel-logos/';
$file_size = $_FILES['HOT_Logo']['size'];
// Resize
$ratio = $width/$height;
if($ratio > 1) {
$new_width = 300;
$new_height = 300/$ratio;
}
else {
$new_width = 300*$ratio;
$new_height = 300;
}
$src = imagecreatefromstring(file_get_contents($file_tmp_name));
$dst = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($src);
imagepng($dst, $file_target.$file_name);
imagedestroy($dst);
// Rename file
$temp = explode('.', $_FILES['HOT_Logo']['name']);
$newfilename = 'new_img_name.'.end($temp);
// Upload image
if(move_uploaded_file($_FILES['HOT_Logo']['tmp_name'], $file_target.$newfilename)) {
...
}
Problem with this script is it upload two image:
The renamed image but unresized.
The non renamed image but resized.
Why ?
You are creating a image, then moving the uploaded file, which is why it's creating two files. I believe your code is supposed to be:
$file_name = $_FILES['HOT_Logo']['name'];
$file_tmp_name = $_FILES['HOT_Logo']['tmp_name'];
$file_target = '../../images/hotel-logos/';
$file_size = $_FILES['HOT_Logo']['size'];
// Resize
$ratio = $width/$height;
if($ratio > 1) {
$new_width = 300;
$new_height = 300/$ratio;
}
else {
$new_width = 300*$ratio;
$new_height = 300;
}
// Rename file
$temp = explode('.', $file_name);
$newfilename = 'new_img_name.'.end($temp);
// Upload image
if(move_uploaded_file($file_tmp_name , $file_target.$newfilename)) {
$src = imagecreatefromstring(file_get_contents($file_target.$newfilename));
$dst = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($src);
imagepng($dst, $file_target.$newfilename);
imagedestroy($dst);
....
}
Related
I need to resize image to 150 x 150 px and then upload it to Amazon S3
Following is the code:
$image = $_FILES["userImage"]["name"];
$fileTempName = $_FILES['userImage']['tmp_name'];
$new_width = 150;
$new_height = 150;
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromstring(file_get_contents($fileTempName));
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, imagesx($image), imagesy($image));
$newFielName = tempnam(sys_get_temp_dir(), "tempfilename");
imagepng($image_p, $newFielName, 9);
$s3 = new S3(awsAccessKey, awsSecretKey);
//move the file
if ($s3->putObjectFile($fileTempName, "urimages", $newFielName, S3::ACL_PUBLIC_READ)) {
$image_link = 'https://s3-us-west-2.amazonaws.com/urimages/' . $newFielName . '';
$this->Product->saveField('image', $image_link);
}
Following is the link which i receive upon uploading : https://s3-us-west-2.amazonaws.com/urimages/C:/Users/LS/AppData/Local/Temp/9102.tmp
Could be you please help me debug the code
i think issue in path. Please create folder on s3 and make a valid
path according to that folder
https://s3-us-west-2.amazonaws.com/urimages/C:/Users/LS/AppData/Local/Temp/9102.tmp
Example :- Resampling an image proportionally
<?php
// The file
$filename = 'test.jpg';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
I want a site where user can upload many picture at a time, how can I reduce the size of multiple image uploaded by single user.
DS in my code is DIRECTORY_SEPARATOR define in initialize file.
if(isset($_POST['submitImage'])){
$file = $_FILES['upload'];
$errors = array();
if(empty($file)){
$errors[] = ' The file could not be empty ';
}else{
foreach( $file['name'] as $key => $value ){
$extensions = array("jpeg","jpg","png");
$file_ext=explode('.',$file['name'][$key]) ;
$file_ext=end($file_ext);
if(in_array($file_ext,$extensions ) === false){
$errors[]="extension not allowed";
}else{
$filetmp = $file['tmp_name'][$key];
$terget_path = SITE_ROOT.'j2reimage'.DS;
$dat = strftime("%Y-%m-%d %H:%M:%S", time());
if(file_exists($terget_path)){
move_uploaded_file( $filetmp, $terget_path.$file['name'][$key]);
mysql_query("insert into 4j2memberimage values ('', $memmem->id,'{$file['name'][$key]}', '$dat')");
//end of if file_exists
}else{
$errors[] = ' Upload extention could not be locate';
}
}
//redirect_to('inb.php');
}
}
}
From PHP.net Originaly posted in comments, but moved to answer as it fixed the OPs problem.
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
this is my script below which i use to re-size the images. My problem is that this script generates negative images (like negative films [with only .png files]) . Where/What is the problem ?
I used GD library to re-size the images but I got same result.
$dir = "../images/sliderimages/";
$photo = $_FILES['slid_image_upload']['name'];
$tmp_name = $_FILES['slid_image_upload']['tmp_name'];
$filename = $dir.$photo;
$dir_thm = "../images/thm_sliderimages/";
$thm_filename = $dir_thm.'thm_'.$photo;
/************Resizing the image***************/
$size = getimagesize($tmp_name);
$width = $size[0];
$height = $size[1];
$newheight = 200;
$newwidth = 420;
$newheight_thm = 50;
$newwidth_thm = 80;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$tmp_thm=imagecreatetruecolor($newwidth_thm, $newheight_thm);
if($size[2] == IMAGETYPE_GIF)
{
$src = imagecreatefromgif($tmp_name);
imagecopyresampled($tmp,$src, 0,0,0,0, $newwidth, $newheight, $width, $height);
imagecopyresampled($tmp_thm, $src, 0,0,0,0, $newwidth_thm, $newheight_thm, $width, $height);
imagegif($tmp,$filename,100);
imagegif($tmp_thm,$thm_filename,100);
}
elseif($size[2] == IMAGETYPE_JPEG)
{
$src = imagecreatefromjpeg($tmp_name);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp_thm, $src, 0,0,0,0, $newwidth_thm, $newheight_thm, $width, $height);
imagejpeg($tmp,$filename,100);
imagejpeg($tmp_thm,$thm_filename,100);
}
elseif($size[2] == IMAGETYPE_PNG)
{
$src = imagecreatefrompng($tmp_name);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp_thm, $src, 0,0,0,0, $newwidth_thm, $newheight_thm, $width, $height);
imagepng($tmp,$filename,9);
imagepng($tmp_thm,$thm_filename,9);
}
imagedestroy($src);
imagedestroy($tmp);
I'd advice you to try you code on another server\local machine to became sure that it's not current library installation issues.
Do any of you know of a good php class I can use to download an image from a remote source, re-size it to 120x120 and save it with a file name of my choosing?
So basically I would have an image at "http://www.site.com/image.jpg" save to my web server "/images/myChosenName.jpg" as a 120x120 pixels.
Thanks
You can try this:
<?php
$img = file_get_contents('http://www.site.com/image.jpg');
$im = imagecreatefromstring($img);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = '120';
$newheight = '120';
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,'/images/myChosenName.jpg'); //save image as jpg
imagedestroy($thumb);
imagedestroy($im);
?>
More information about PHP image function : http://www.php.net/manual/en/ref.image.php
You can resize keeping the ratio of image
$im = imagecreatefromstring($img);
$width_orig = imagesx($im);
$height_orig = imagesy($im);
$width = '800';
$height = '800';
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
If you're looking to have the ability to do this for both jpg and png file formats, here's what helped me:
$imgUrl = 'http://www.example.com/image.jpg';
// or $imgUrl = 'http://www.example.com/image.png';
$fileInfo = pathinfo($imgUrl);
$img = file_get_contents($imgUrl);
$im = imagecreatefromstring($img);
$originalWidth = imagesx($im);
$originalHeight = imagesy($im);
$resizePercentage = 0.5;
$newWidth = $originalWidth * $resizePercentage;
$newHeight = $originalHeight * $resizePercentage;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
if ($fileInfo['extension'] == 'jpg') {
imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagejpeg($tmp, '/img/myChosenName.jpg', -1);
}
else if ($fileInfo['extension'] == 'png') {
$background = imagecolorallocate($tmp , 0, 0, 0);
imagecolortransparent($tmp, $background);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagepng($tmp, '/img/myChosenName.png');
}
else {
// This image is neither a jpg or png
}
imagedestroy($tmp);
imagedestroy($im);
The extra code on the png side of things ensures that the saved image contains any and all transparent sections.
I have a bit of code that generates thumbnails from an uploaded image. The only problem is that it cuts portrait images off, rather than resizing the portrait image to fit the height of the thumbnail, landscape images are fine. I was wondering if anyone could help me out to change the code so it will place portrait images inside the thumbnail properly? (if that makes sense?)
Here's the code:
$setSize = 150;
$setHSize = 113;
$jpeg_quality = 75;
list($width, $height, $type, $attr) = getimagesize($origPath);
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
$img_r = imagecreatefromjpeg($origPath) or notfound();
$dst_r = ImageCreateTrueColor( $setSize, $setHSize );
$heightOffset = round( ($setHSize-$newH)/2 );
$white = imagecolorallocate($dst_r, 255, 255, 255);
imagefilledrectangle($dst_r, 0, 0, $setSize, $setHSize, $white);
imagecopyresampled($dst_r, $img_r, 0, $heightOffset, 0, 0, $newW, $newH, $width, $height);
header("Content-type: image/jpeg");
imagejpeg($dst_r, $thbPath, $jpeg_quality);
I just don't fully understand the way php creates images, so any help would be appreciated :)
The way you compute $newW and $newH is incorrect for what you want. You are giving preference to the width, so most landscape images will look okay, but portrait will be cut off. Try the following instead:
// assume landscape and see how things look
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
if ($newH > $setHSize) {
// portrait image
$newH = $setHSize;
$newW = round( $width * ( $setHSize / $height ) );
}
I hope this helps!
Hope this helps.
<?php
define('DOCROOT', $_SERVER['DOCUMENT_ROOT']);
include_once(DOCROOT."/dbc.php");
//**********************| Resize based on height
$photo_height = 350;
//**********************| Get the file from the post
$file = $_FILES['file'];
$path_thumbs = (DOCROOT."/gallery/");
$path_big = (DOCROOT."/trash/");
//**********************| Check permission
if (!is_writeable($path_thumbs)){
die ("Error: The directory <b>($path_thumbs)</b> is NOT writable");
}
if (!is_writeable($path_big)){
die ("Error: The directory <b>($path_big)</b> is NOT writable");
}
//**********************| Make sure you have a file
if (isset($file)){
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//**********************| Make new name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//**********************| See the kind of file we have
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}
elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}
elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//**********************| Get the height and width
list($width, $height) = getimagesize($file_tmp);
$imgratio=$height/$width;
if ($photo_height >= $height){
//*********** Dont resize if the image is smaller then $photo_height = 350;
$newwidth = $width;
$newheight = $height;
}
elseif ($imgratio>1){
$newheight = $photo_height;
$newwidth = $photo_height/$imgratio;
}
else{
$newwidth = $photo_height;
$newheight = $photo_height*$imgratio;
}
if (function_exists(imagecreatetruecolor)){ $resized_img = imagecreatetruecolor($newwidth,$newheight); }
else{ die("Error: Please make sure you have GD library ver 2+");
}
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext",'100');
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
$newimage = "$rand_name.$file_ext";
}
else {
echo "Sorry, there was a problem, Please try again.\n\n";
}
adaptiveResizeImage
or
adaptiveCropThumblanil
in Imagick can help you