help needed to resize an image in php - php

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

Related

Change width and height of an image with aspect ratio

I have this code, for changing the width of the image:
function resize_img($file,$width,$height=null){
$ext = pathinfo($file, PATHINFO_EXTENSION);
if($ext=='jpg' || $ext=='jpeg'){
$img = imagecreatefromjpeg($file);
} else if($ext=='png'){
$img = imagecreatefrompng($file);
}
$img_w = imagesx($img);
$img_h = imagesy($img);
$ratio = $width / $img_w;
$new_h = $img_h * $ratio;
$new_h = $height??$new_h;
$new_img = imagecreatetruecolor($width,$new_h);
imagecopyresampled($new_img, $img, 0, 0, 0, 0, $width, $new_h, $img_w, $img_h);
if($ext=='jpg' || $ext=='jpeg'){
imagejpeg($new_img, $file, 82);
} else if($ext=='png'){
imagepng($new_img, $file);
}
}
I would like to add the ability to change the width along with the height while keeping the aspect. Now resolution is changing, but isn't filled (it's streched) How can I do that? Is this possible?

Resize, rename and upload image with PHP

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

How to resize image in this PHP script?

I'm experimenting with php script via ajax which uploads an array of images from this source.
While it works excellent I'm trying to enter php code which resizes images to 120px by width or height (whichever is larger).
For my sanity please help how to update code:
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
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('Only '.implode(',',$allowed_ext).' files are allowed!');
}
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:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
You can install imagemagick on your server:
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
$img = new Imagick($file);
if ($crop) {
$img->cropThumbnailImage($w, $h);
} else {
$img->thumbnailImage($w, $h, TRUE);
}
return $img;
}
resize_image(‘/path/to/some/image.jpg’, 150, 150);
Another way would be using the PHP-GD:
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
$img = resize_image(‘/path/to/some/image.jpg’, 150, 150);
<?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);
Find more at php.net
Well, I took an example of "promaty" from this LINK and call from loop:
<?php
$dir = "uploads/*.*";
$images = glob( $dir );
foreach( $images as $file ):
$px = 120;
$prefix = $px . "_";
$dst = "uploads/" . $prefix . basename($file);
$resized = image_resize($file, $dst, $px, $px);
echo "<img src='" . $dst . "' />";
echo "<p>" . basename($dst) . " </p>";
endforeach;
...and thanks for your time.

Changing image width when sending via header in php

I have this piece of code that calls a random image and sends it to another page. That page calls this script via an image link. What I am trying to figure out is how to make it specify an image width when the image is past my max width. I got this far then got completely lost.
<?php
$folder = '';
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1;
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) {
if (preg_match('/\.'.$ext.'$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
closedir($handle);
mt_srand((double)microtime()*1000000);
$rand = mt_rand(0, $i);
$image =($folder.$files[$rand]);
if (file_exists($image))
{
list($width) = getimagesize($image);
$maxWidth = 150;
if ($width > $maxWidth)
{
header('Location: '.$folder.$files[$rand]); // Voila!;
}
else
{
header('Location: '.$folder.$files[$rand]); // Voila!
}
}
?>
You could use CSS max-width and max-height properties.
Here isa couple of resize functions, I think at least one of them maintains the aspect ratio.
function resize_image($file, $w, $h, $crop = false) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And:
function thumb_aspect_crop($source_path, $desired_width, $desired_height) {
list( $source_width, $source_height, $source_type ) = getimagesize($source_path);
switch ($source_type) {
case IMAGETYPE_GIF:
$source_gdim = imagecreatefromgif($source_path);
break;
case IMAGETYPE_JPEG:
$source_gdim = imagecreatefromjpeg($source_path);
break;
case IMAGETYPE_PNG:
$source_gdim = imagecreatefrompng($source_path);
break;
}
$source_aspect_ratio = $source_width / $source_height;
$desired_aspect_ratio = $desired_width / $desired_height;
if ($source_aspect_ratio > $desired_aspect_ratio) {
// Triggered when source image is wider
$temp_height = $desired_height;
$temp_width = (int) ( $desired_height * $source_aspect_ratio );
} else {
// Triggered otherwise (i.e. source image is similar or taller)
$temp_width = $desired_width;
$temp_height = (int) ( $desired_width / $source_aspect_ratio );
}
// Resize the image into a temporary GD image
$temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
imagecopyresampled(
$temp_gdim,
$source_gdim,
0, 0,
0, 0,
$temp_width, $temp_height,
$source_width, $source_height
);
// Copy cropped region from temporary image into the desired GD image
$x0 = ( $temp_width - $desired_width ) / 2;
$y0 = ( $temp_height - $desired_height ) / 2;
$desired_gdim = imagecreatetruecolor($desired_width, $desired_height);
imagecopy(
$desired_gdim,
$temp_gdim,
0, 0,
$x0, $y0,
$desired_width, $desired_height
);
return $desired_gdim;
}
Try to use Primage class, like in example
You can not specify that in the header. There are 2 ways to go about it.
1 : in the image tag, specify the width attribute, however this will force the smaller images to scale up as well, so probably not the best course of action.
2 : Resize the image on the fly with GD library and send the resultant image instead of the original.
Edit:
For resizing you may look into this very simple to use image resize class.
http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth($maxWidth);
$image->save('picture2.jpg');
Now you can redirect to picture2.jpg or send the image content inline. Also if the image is used often, then check on top of the script, if your resized image exists, if it does send it otherwise continue to resize.

Cropping an image in PHP

I am doing PNG image cropping using this function. Everything is working fine, but whenever I upload the .png, the image background color is changed to black. Here is the code.
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments3";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
} `
even i tried like this also
/************************************Resizing the image 80*60****************/
$path3="partners_logs";
$filetype3=$_FILES["pimage"]["type"];
$bgim_file_name = $path3."/".$Attachments2;
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
imageAlphaBlending($bgim_old, true);
imageSaveAlpha($bgim_old, true);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments2";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
//set the background color to your choice, paramters are int values of red,green and blue
imagecolorallocate($bgim_new,0xFF,0xFF,0xFF);
}
/************End Resize of 80*60*******************/
maybe this helps
Don't forget about
imagealphablending() and
imagesavealpha() if you're working
with [semi]transparent png.
<?php
$file = 'semitransparent.png'; // path to png image
$img = imagecreatefrompng($file); // open image
imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)
found at php.net - imagecreatefrompng under User Contributed Notes
NOT tested
edit see comment
<?php
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
imageAlphaBlending($bgim_new, true);
imageSaveAlpha($bgim_new, true);
?>
After some testing and reading througt several pnp.net comments i've got a working script
<?php
$newImageName = "PNG_transparency_copy.png";
$newWidth = 265;
$newHeight = 150;
$orgAttribs = getimagesize("PNG_transparency_demonstration_1.png");
$orginal = imagecreatefrompng("PNG_transparency_demonstration_1.png");
imagesavealpha($orginal, true);
$newPng = imagecreatetruecolor($newWidth,$newHeight);
imagealphablending($newPng, false);
$color = imagecolortransparent($newPng, imagecolorallocatealpha($newPng, 0, 0, 0, 127));
imagefill($newPng, 0, 0, $color);
imagesavealpha($newPng, true);
imagecopyresampled($newPng,$orginal,0,0,0,0,$newWidth,$newHeight, $orgAttribs[0], $orgAttribs[1]);
header("Content-type: image/png");
imagepng($newPng,$newImageName);
PNG taken from Wikipedia
Try This Function....
<?php
function CropImg($img_dst, $img_src, $dst_width = 300, $dst_height = 180){
$ext = pathinfo($img_src, PATHINFO_EXTENSION);
if($ext != 'jpg' and $ext != 'jpeg'){
$image = imagecreatefrompng($img_src);
}else{
$image = imagecreatefromjpeg($img_src);
}
$filename = $img_dst;
$thumb_width = $dst_width;
$thumb_height = $dst_height;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
if($ext == 'png'){
imagealphablending($thumb, false);
$white = imagecolorallocatealpha($thumb, 0, 0, 0, 127); //FOR WHITE BACKGROUND
imagefilledrectangle($thumb,0,0,$thumb_width,$thumb_height,$white);
imagesavealpha($thumb, true);
}
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
if($ext == 'png'){
imagepng($thumb, $filename);
}else{
imagejpeg($thumb, $filename, 80);
}
return true;
}
CropImg("photo.png", "result.png", 300, 180);
?>

Categories