can not crop thumbnail of passed size - php

I have an image whose size is "300X367" .
I have an image function which crop thumbnail by using this type
but this function crop thumbnail of "41X50". I think it crop thumbnail by scale of original image.
But I want accurate thumbnail size of passing parameter. I can't put code here of image.php as the size is too big.
If anyone have solution for passing size parameter in image tag & crop thumbnail. please tell me.

Try this example code
<?php
function getFileExtenction($image)
{
$imageAry = explode(".", $image);
return $imageAry[1];
}
$image = 'images/imageName.png'; //Your image location
$imageType = getFileExtenction($image); //check the image file type
if ($imageType == "png")
$src = imagecreatefrompng($image);
else if ($imageType == "jpg")
$src = imagecreatefromjpeg($image);
else if ($imageType == "gif")
$src = imagecreatefromgif($image);
else
{
}
list($width, $height) = getimagesize($image); //To get the image width and height
$newwidth = 41; //Give your thumbanail image width
$newheight = 50; //Give your thubnail image height
$tmp = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename = "NewImagename." . $imageType;
/*========== if you want to store this file in a folder Ex: "thumbs" ==========
$filename = "thumbs/NewImagename." . $imageType;
*/
imagejpeg($tmp, $filename, 100);
imagedestroy($src);
imagedestroy($tmp);
?>

Related

Photo has wrong colors after resized with PHP script

I'm using the following PHP function to resize big images to fit 500 px width:
<?php
function resizeImage($name) {
header('Content-type: image/jpeg');
$filename = "file.jpg";
$new_width = 500;
list($width, $height) = getimagesize($filename);
$new_height = (($height*$new_width)/$width);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, "file.jpg", 100);
}
?>
For some reason the colors on the resized image aren't exactly the same as before. They aren't as clear and strong as before. As you can see [picture removed] there's more red color and brilliance in the left (original) photo.
Why that? Is there something wrong with my script? Or is it a normal resizing effect?
This is the working code I have now:
<?php
// Call the function with: resizeImage("INSERT_YOUR_FILE_NAME_INCLUDING_SUFFIX_HERE");
function resizeImage($file_name) {
// File is located at: files/original/
$filename = "files/original/".$file_name;
// The width you want the converted image has
$new_width = 500;
// Calculate right height
list($width, $height) = getimagesize($filename);
$new_height = (($height*$new_width)/$width);
// Get image
$small = new Imagick($filename);
// Resize image, but only if original image is wider what the wanted 500 px
if($width > $new_width) {$small->resizeImage($new_width, $new_height, Imagick::FILTER_LANCZOS, 1);}
// Some code to correct the color profile
$version = $small->getVersion();
$profile = "sRGB_IEC61966-2-1_no_black_scaling.icc";
if((is_array($version) === true) && (array_key_exists("versionString", $version) === true)) {$version = preg_replace("~ImageMagick ([^-]*).*~", "$1", $version["versionString"]);if(is_file(sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version)) === true) {$profile = sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version);}}if(($srgb = file_get_contents($profile)) !== false){$small->profileImage("icc", $srgb);$small->setImageColorSpace(Imagick::COLORSPACE_SRGB);}
// Safe the image to: files/small/
$small->writeImage("files/small/".$file_name);
// Clear all resources associated to the Imagick object
$small->clear();
}
?>
Don't forget to either download the icc file from http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc and save it in the same directory as your resize file or change $profile = "sRGB_IEC61966-2-1_no_black_scaling.icc"; to $profile = "http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc";!

In PHP, how do you add whitespace around a non-square photo, so that it is always 200x200 pixels?

This script below works fine to handle an uploaded image and resize it so that the max height or width (whichever side is longer) is 200px. So it could be 200x200 if it's perfect square image, or 200x140, or 140x200, etc.
if(isset($_FILES['image'])) {
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists for this pool and removing if so, before adding new image in its place
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// checks valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid . ".png";
$path = "uploads/".strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst, $path); // adjust format as needed
imagedestroy($dst);
$_SESSION['image_uploaded']="yes";
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
Now, Facebook sharing using OpenGraph requires an image to be at least 200x200. So a 140x200 image wouldn't work with their sharing functionality.
I don't love non-square images anyway, so I would like to take the image and if it's not already a square, I'd like to add whitespace to the sides (or on the top/bottom) and save it as a perfect 200x200 square every single time.
I tried this below, but it's not working (no image gets created at all). What is wrong with what I tried to do? This doesn't seem overly complicated but clearly I'm missing something.
if(isset($_FILES['image'])) {
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists for this pool and removing if so, before adding new image in its place
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// checks valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid . ".png";
$path = "uploads/".strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
$orig_img=imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
// create new image and fill with background colour
$new_img = imagecreatetruecolor($output_w, $output_h);
$bgcolor = imagecolorallocate($new_img, 255, 0, 0); // red
imagefill($new_img, 0, 0, $bgcolor); // fill background colour
// copy and resize original image into center of new image
$final_img=imagecopyresampled($new_img, $orig_img, 0, 0, 0, 0, 200, 200, $width, $height);
imagepng($final_img, $path); // adjust format as needed
imagedestroy($dst);
$_SESSION['image_uploaded']="yes";
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
You don't need a temporary intermediate image. You can paste the resampled source image right into the destination image after you fill it with background. See here:
$src = imagecreatefromstring(file_get_contents($tmp));
// Create new image and fill it with background color
$dst = imagecreatetruecolor($output_w,$output_h);
$bgcolor = imagecolorallocate($dst, 255, 0, 0);
imagefill($dst, 0, 0, $bgcolor);
// Copy resampled src image into dst
if ($ratio > 1)
imagecopyresampled($dst, $src, 0, ($output_h - $height) / 2, 0, 0, $width, $height, $size[0], $size[1]);
else
imagecopyresampled($dst, $src, ($output_w - $width) / 2, 0, 0, 0, $width, $height, $size[0], $size[1]);
imagepng($dst, $path); // adjust format as needed
imagedestroy($src);
imagedestroy($dst);

Using imagejpeg() save to folder but doesn't preview image on the browser

Index.php
<?php
error_reporting(E_ALL);
// File and new size
//the original image has 800x600
$filename = 'images/lazy1.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb, "raj.jpg", 100);
imagedestroy($thumb);
echo "Image Resize Successfully";
?>
I am using imagejpeg() to save file. i want save file in folder but not show on browser. in browser only show this message "Image Resize successfully".
<?php
error_reporting(E_ALL);
// File and new size
//the original image has 800x600
$filename = 'images/lazy1.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
//Removed lines here
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb, "raj.jpg", 100);
imagedestroy($thumb);
echo "Image Resize Successfully";
?>

Making Thumbnails, but having trouble with PNG

I'm creating thumbnails using php, and it is working fine for GIF and JPEG, but not for PNG. When I run this script, with a PNG, a thumbnail doesn't save. Can you show me what I am doing wrong? Thanks in advance!
public function make_thumbs($img_src)
{
//Desired thumbnail width
$width = 100;
//Thumbnail name
$thumb = 'th_' . $img_src;
//Ensure the image exists
if(file_exists($img_src)){
if (exif_imagetype($img_src) == IMAGETYPE_GIF)
{
//Create image stream
$image = imagecreatefromgif($img_src);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_JPEG)
{
//Create image stream
$image = imagecreatefromjpeg($img_src);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_PNG)
{
//Create image stream
$image = imagecreatefrompng($img_src);
}
//Gather and store the width and height
list($image_width, $image_height) = getimagesize($img_src);
//Calculate new height while maintaining aspect ratio
$height = (($width / $image_width) * $image_height);
//Resample/resize the image
$tmp_img = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp_img, $image, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
//Attempt to save the new thumbnail
if(is_writeable(dirname($thumb)))
{
if (exif_imagetype($img_src) == IMAGETYPE_GIF)
{
imagegif($tmp_img, $thumb, 100);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_JPEG)
{
imagejpeg($tmp_img, $thumb, 100);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_PNG)
{
imagepng($tmp_img, $thumb, 100);
}
}
//clear memory
imagedestroy($tmp_img);
imagedestroy($image);
}
}

PHP-GD Image re-size loses the quality of the image

I've made this piece of code, it will re-size images on the fly, if it can't find the requested image, and then stores it.
The only problem with this is that the output jpg image has a low quality.
I was wondering if there is something I need to change to improve the image quality.
if (isset($_GET['size'])) {
$size = $_GET['size'];
}
if (isset($_GET['name'])) {
$filename = $_GET['name'];
}
$filePath = "files/catalog/" . urldecode($filename);
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filePath);
if ($_GET["name"] && !$size) {
$newwidth = $width * $percent;
$newheight = $height * $percent;
} else if ($_GET["name"] && $size) {
switch ($size) {
case "thumbs":
$newwidth = 192;
$newheight = 248;
break;
case "large":
$newwidth = 425;
$newheight = 550;
break;
}
}
$resizedFileName = $filename;
$resizedFileName = str_replace(".jpg", "", $resizedFileName) . ".jpg";
$resizedFilePath = "files/catalog/" . urldecode($resizedFileName);
if (!file_exists($resizedFilePath)) {
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filePath);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb, $resizedFilePath);
//file_put_contents($, $binarydata);
$imageContent = file_get_contents($resizedFilePath);
echo $imageContent;
} else {
$imageContent = file_get_contents($resizedFilePath);
echo $imageContent;
}
Instead of imagecopyresized() you must use imagecopyresampled() and imagejpeg() function has third optional parameter and you can specify quality.
Probably because you are using imagejpeg() wrong, the second variable in the functions stands for the quality in percentage!
You want imagecopyresampled(). resize works by throwing away unecessary pixels. resampled() will average things out and produce much smoother results.

Categories