PHP temporary thumbnail - php

I'm not after saving an image, I just want to scale down an image by percentage and then display it on a webpage
I know I can use getimagesize to get the height width but how to scale correctly?

You can use a function like this .
Refer http://tutorialfeed.net/development/scale-an-image-using-php
function create_thumb( $imgSrc, $thumbnail_width, $thumbnail_height, $dest_src, $ext )
{
//getting the image dimensions
list( $width_orig, $height_orig ) = getimagesize( $imgSrc );
// Check if the images is a gif
if( $ext == 'gif' )
{
$myImage = imagecreatefromgif($imgSrc);
}
// Check if the image is a png
elseif( $ext == 'png' )
{
$myImage = imagecreatefrompng($imgSrc);
}
// Otherwise, file is jpeg
else
{
$myImage = imagecreatefromjpeg($imgSrc);
}
// Find the original ratio
$ratio_orig = $width_orig / $height_orig;
// Check whether to scale initially by height or by width
if( $thumbnail_width / $thumbnail_height > $ratio_orig )
{
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
}
else
{
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width / 2; //horizontal middle
$y_mid = $new_height / 2; //vertical middle
$process = imagecreatetruecolor( round( $new_width ), round( $new_height ) );
// Scale the image down and the reduce the other axis to create the thumbnail
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
// Depending on the file extension, save the file
if( $ext == 'gif' )
{
imagegif( $thumb, $dest_src );
}
elseif( $ext == 'png' )
{
imagepng( $thumb, $dest_src );
}
else
{
imagejpeg( $thumb, $dest_src, 100 );
}
// Remove rubbish file data
imagedestroy($process);
imagedestroy($myImage);
// Return thumb ( success / fail )
return $thumb;
}

You can use the resizeInPourcent() method of ImageWorkshop (a library using the GD library): http://phpimageworkshop.com/doc/17/resizing.html
Ex:
<?php
$myImage->resizeInPourcent(50, 50); // Resize to get 50% width and height

Related

thumbnail Image is not rotating

I am creating a thumbnail in php for the uploaded image. The thumbnail is created and saved correctly but it is not rotating when needed. I test my code on many images but it did not work. Here is my code for creating the thumbnail and rotate it based on its exif data.
//thumb image
$maxDim = 300;
$filename = $_FILES['file']['name'];
list($width, $height, $type, $attr) = getimagesize($path.$filename);
if ( $width > $maxDim || $height > $maxDim )
{
$ext = pathinfo($filename, PATHINFO_EXTENSION); //var_dump($ext);
$target_filename = $path.'thumb_'.$filename;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$contents = file_get_contents($path.$filename);
$src = imagecreatefromstring($contents);
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
$exif = exif_read_data($path.$filename);
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$dst = imagerotate($dst, 180, 0);
break;
case 6:
$dst = imagerotate($dst, 90, 0);
break;
case 8:
$dst = imagerotate($dst, -90, 0);
break;
}
}
//check src image type
if (exif_imagetype($path.$filename ) == IMAGETYPE_JPEG) {
imagejpeg($dst, $target_filename );
}
else if(exif_imagetype($path.$filename ) == IMAGETYPE_PNG){
imagepng($dst, $target_filename );
}
else if(exif_imagetype($path.$filename ) == IMAGETYPE_GIF){
imagegif($dst, $target_filename );
}
imagedestroy( $dst );
}

how to resize the image size while uploading the image to the folder

<?php
include 'config.php';
$name = $_POST['name'];
$image = $_POST['image'];
//image in string format //decode the image
$imageconverting = base64_decode($image);
//upload the image
file_put_contents("pets_imgs/".$name.".jpg", $imageconverting);
?>
how to resize the image size while uploading the image to the folder
you can implement image resize using this library
use class.upload.php
library for image resize
or using below code
maxDim = 800;
list($width, $height, $type, $attr) = getimagesize( $_FILES['myFile']['tmp_name'] );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $_FILES['myFile']['tmp_name'];
$fn = $_FILES['myFile']['tmp_name'];
$size = getimagesize( $fn );
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = $maxDim;
$height = $maxDim/$ratio;
} else {
$width = $maxDim*$ratio;
$height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $fn ) );
$dst = imagecreatetruecolor( $width, $height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}

crop an image after resizing in GD library

I need to first resize an image proportionally (the width is the important dimension) and then crop afterwards to chop of any excess height and then store the new version in a directory.
I've managed to do the resizing fine and I end up with images that are the correct width in my directory. Somehwere in here I need to crop the excess height off. But I can't work out where I need to do it. Do I need to use copyimageresampled somehow. I want to crop all images so they're 50px in height.
Here's what I have so far fo the resizing:
$src = ImageCreateFromJpeg($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
ImageJpeg($dst, 'images/' . $_FILES['image']['name']);
This is what I was after. A 2 stage process. The trick is to resize the image in to a temporary image and then crop it:
http://salman-w.blogspot.com/2009/04/crop-to-fit-image-using-aspphp.html
This might help you to crop after resize: 911-need-code-help
<?php
//----------------------------------------------------------------
// Crop-to-fit PHP-GD
// Revision 2 [2009-06-01]
// Corrected aspect ratio of the output image
//----------------------------------------------------------------
define( 'DESIRED_IMAGE_WIDTH', 150 );
define( 'DESIRED_IMAGE_HEIGHT', 150 );
$source_path = $_FILES[ 'Image1' ][ 'tmp_name' ];
//
// Add file validation code here
//
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_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT;
if ( $source_aspect_ratio > $desired_aspect_ratio )
{
//
// Triggered when source image is wider
//
$temp_height = DESIRED_IMAGE_HEIGHT;
$temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio );
}
else
{
//
// Triggered otherwise (i.e. source image is similar or taller)
//
$temp_width = DESIRED_IMAGE_WIDTH;
$temp_height = ( int ) ( DESIRED_IMAGE_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_IMAGE_WIDTH ) / 2;
$y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2;
$desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT );
imagecopy(
$desired_gdim,
$temp_gdim,
0, 0,
$x0, $y0,
DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT
);
//
// Render the image
// Alternatively, you can save the image in file-system or database
//
header( 'Content-type: image/jpeg' );
imagejpeg( $desired_gdim );
//
// Add clean-up code here
//
?>
Croping is just like resizing with GD
Some sample code:
// Original image
$filename = 'someimage.jpg';
// 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 = 50;
$top = 50;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;
// 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);
You define your crop width & height, and should be all set. Its not much more than a resize as you can see.
Reference: http://www.johnconde.net/blog/cropping-an-image-with-php-and-the-gd-library/

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.

Problem in creating thumbnail of png image !

I have used the following php function to create thumbnail image.
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
$dir = opendir( $pathToImages );
while (false !== ($fname = readdir( $dir ))) {
$info = pathinfo($pathToImages . $fname);
if ( strtolower($info['extension']) == 'jpg' || strtolower($info['extension']) == 'png' )
{
// load image and get image size
if(strtolower($info['extension']) == 'jpg')
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
else
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new tempopary 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 );
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
if(strtolower($info['extension']) == 'jpg')
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
else
imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
Proper thumbnail is created for jpg image. But for png transparent image, thumbnail is created with black background. How do I make function work for png image? Please do suggest me. Thanks in advance.
I don't remember the exact particulars, but you'll want to read up on, and experiment with imagesavealpha() and imageaplphablending()
If memory serves me correctly, you'll want to set imagealphablending off, and then set imagesavealpha true. (In fact, yes, the manual page for imagesavealpha() implies just that)
So, at the end of your code:
// save thumbnail into a file
if(strtolower($info['extension']) == 'jpg'){
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}");
}else{
imagealphablending($tmp_img,false);
imagesavealpha($tmp_img,true);
imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}
Are you trying to reinvent the wheel? Use php Thumbnailer :)
<?php
// load the library
require 'Thumbnailer';
// make callback function
function myfunc(& $thumb) {
// that will make a image thumbnail square 100x100px
$thumb->thumbSquare(100)->save('photos/output/'.$thumb->filename);
}
// call batch helper
// find all jpg, png and gif images in /photos/directory
Thumbnailer::batch('myfunc', '/photos/directory/*.{jpg,png,gif}');
?>
That's easy.

Categories