Image crop function not working in Wordpress - php

I have used this following function in my localhost which is working fine
// Image cropping
function cropImage($sourcePath, $thumbSize, $destination = null) {
$parts = explode('.', $sourcePath);
$ext = $parts[count($parts) - 1];
if ($ext == 'jpg' || $ext == 'jpeg') {
$format = 'jpg';
} else {
$format = 'png';
}
if ($format == 'jpg') {
$sourceImage = imagecreatefromjpeg($sourcePath);
}
if ($format == 'png') {
$sourceImage = imagecreatefrompng($sourcePath);
}
list($srcWidth, $srcHeight) = getimagesize($sourcePath);
// calculating the part of the image to use for thumbnail
if ($srcWidth > $srcHeight) {
$y = 0;
$x = ($srcWidth - $srcHeight) / 2;
$smallestSide = $srcHeight;
} else {
$x = 0;
$y = ($srcHeight - $srcWidth) / 2;
$smallestSide = $srcWidth;
}
$destinationImage = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
if ($destination == null) {
header('Content-Type: image/jpeg');
if ($format == 'jpg') {
imagejpeg($destinationImage, null, 100);
}
if ($format == 'png') {
imagejpeg($destinationImage);
}
if ($destination = null) {
}
} else {
if ($format == 'jpg') {
imagejpeg($destinationImage, $destination, 100);
}
if ($format == 'png') {
imagepng($destinationImage, $destination);
}
}
}
But i am using this in my wordpress theme and it is showing some errors
����JFIF����?I��^��l�i�����76����6m�0ib�~���X��KR����J��W�9��.�7wK~��J��)�J��)�.�������A�_�]�pw��#��'��{1M{���5���7�#X��|�w�#9W^�t�]������t}ms�l���%���W{���G��1T+8�2s���0a��3�XX� �yL��FrU��#�Y٦'���r���{g��簪�;c�[�0r0q�q���N9��G��{?�c�w�K�ӯE�|ެ�Td2���F�?!#�G�z>ЀP�����u۝�ᓒ����d��A8��9't��=���b���'#'ג}O��\����P�S�]���o�h�Zy$|�Ns�q��Y��t8f+�O�
I have used this code for showing the image
$docimg = $doctor_img['url'];
if ($docimg):
?>
<?php cropImage( $docimg, 200, null); ?>
Is there anything to change in this code. So that i can get the image src instead of wired characters

I have found a solution for this,but i cant understand what will happen if png file will come.
ob_start();
header( "Content-type: image/jpeg" );
cropImage( $docimg, 200, null);
$i = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>";
Because as you see, there is written for jpeg file only.

here is the working example
$parts = explode('.', $docimg);
$ext = $parts[count($parts) - 1];
if ($ext == 'jpg' || $ext == 'jpeg') {
$format = 'jpg';
} else {
$format = 'png';
}
ob_start();
header( "Content-type: image/".$format );
cropImage( $docimg, 200, null);

Related

Error while creating thumbnail in php for multiple image upload

I use following code to upload, rename, compress, create thumbnail everything works fine, And recently i noticed while creating thumb it creates fresh copy of thumb images for previously uploaded images also(create thumbnail for uploaded and uploading images too)
Problem:
When form is submitted it crates thumb for uploading image and uploaded images(image file that are present in older).
how do i solve this problem
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
if
(move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['tmp_name'][$key], 0);
}
} else {
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key + 1) . ' = $row[0];';
eval($codestr);
} else {
$codestr = '$file' . ($key + 1) . ' = NULL;';
eval($codestr);
}
}
}
$orig_directory = "$desired_dir";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$dir_handle = opendir($orig_directory);
if ($dir_handle > 1) {
$allowed_types = array('jpg', 'jpeg', 'gif', 'png');
$file_type = array();
$ext = '';
$title = '';
$i = 0;
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..') {
continue;
}
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
if (in_array($ext, $allowed_types)) {
$nw = 125;
$nh = 90;
$source = "$desired_dir{$file_name}";
$stype1 = explode(".", $source);
$stype = $stype1[count($stype1) - 1];
$dest = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
compress($source, "$desired_dir/" . $file_name, 50);
}
}closedir($dir_handle);
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file1, PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file2, PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file3, PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file4, PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: /post/price_plan.php');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
} else if ($targetRatio > $srcRatio) {
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
} else {
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
Bounty Edit
if there is any good and faster function to do please.
all i need is to upload, rename, compress, create thumbnail and save name to DB
The code is need much more optimization. you are iterating the file folder again every time instead of looping the just uploaded files.
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$file = [];
$nw = 125;
$nh = 90;
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
$file_name_with_ext = $file_name . $sExt;
$source = = $desired_dir . $file_name_with_ext ;
if(!move_uploaded_file($file_tmp, $source)) {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$file[] = NULL;
}else{
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($sExt) {
case '.gif':
$simg = imagecreatefromgif($source);
break;
case '.jpg':
$simg = imagecreatefromjpeg($source);
break;
case '.png':
$simg = imagecreatefrompng($source);
break;
}
$dest = $thumb_directory. $file_name_with_ext ;
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
// imagewebp($dimg, $dest);
compress($source, "$desired_dir" . $file_name_with_ext , 50);
compress($dest, $dest , 50);
$file[] = $file_name_with_ext ;
}
}else{
// TODO: error handling
}
}
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file[0], PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file[1], PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file[2], PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file[3], PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: https://google.com');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
} else if ($targetRatio > $srcRatio) {
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
} else {
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
?>
As part of your question you asked if there was "any good and faster function to do please."
https://github.com/delboy1978uk/image
Try this! (install via Composer or just require each of the classes in if you just drop the code in yourself)
<?php
use Del\Image;
$image = new Image('/path/to/your.jpg'); //or gif , etc
// Or...
$image = new Image();
$image->load('/path/to/my.png');
You'll then have all of these commands at your disposal:
$image->crop($width, $height, 'center'); // Crops the image, also accepts left or right as 3rd arg
$image->destroy(); // remove loaded image in the class. Frees up any memory
$image->getHeader(); // returns image/jpeg or equivalent
$image->getHeight(); // returns height in pixels
$image->getWidth(); // returns width in pixels
$image->output(); // output to browser
$image->output(true); // passing true returns raw image data string
$image->resize($width, $height); // resize to the given dimensions
$image->resizeAndCrop($width, $height); // resize to the given dimensions, cropping top/bottom or sides
$image->save(); // Save the image
$image->save('/path/to/save.jpg', $permissions, $compression); // Save as a different image
$image->scale(50); // Scale image to a percentage
Loop through your POSTed uploads, load them up, save the original, resize the image, and save the thumbnail. Existing images shouldn't be touched.
There are plenty bad php-programming-habits in that code (e.g. use of eval and general data-flow).
To break it down: The script first validates the uploaded files and moves them to a temp directory. Then it calculates thumbnails for all files in the temp directory.
To change that we use an array which contains the filenames of uploading images.
// ...
$file_type = array();
$ext = '';
$title = '';
$i = 0;
// First change:
$validFileNames = array_column($uploadedFiles, 0);
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..' || !in_array($file_name, $validFileNames)) {
continue;
}
// Nothing changed beyond this point
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
// ...
}
array_column($uploadedFiles, 0) reads the index 0 of every entry in $uploadedFiles, which contains the filename. So $validFileNames contains only filenames of uploading images.
We then check for every file in the temp-directory if its name is included in $uploadedFiles. If not then it was not uploading and can be ignored.
As for the request of a more general optimization:
<?php
$desired_dir = $_SERVER['DOCUMENT_ROOT'].'/upload/file/';
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $uploadedFileName) {
$errors = array();
$destFilename = md5(uniqid('uploads', true).time());
$uploadedSize = $_FILES['files']['size'][$key];
$uploadedTmpName = $uploadedFileName;
$uploadedType = $_FILES['files']['type'][$key];
$sExt = null;
if ($uploadedType == 'image/gif') {
$sExt = '.gif';
} elseif ($uploadedType == 'image/jpeg' || $uploadedType == 'image/pjpeg') {
$sExt = '.jpg';
} elseif ($uploadedType == 'image/png' || $uploadedType == 'image/x-png') {
$sExt = '.png';
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = 'Image types alowed are (.gif, .jpg, .png) only!';
}
if ($uploadedSize > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (!empty($errors)) {
// Todo: Error handling of $errors
continue;
}
if (is_dir($desired_dir) == false) {
mkdir($desired_dir, 0700);
}
$destFilePath = "$desired_dir/".$destFilename.$sExt;
if (!move_uploaded_file($uploadedTmpName, $destFilePath)) {
echo "Couldn't upload file ".$uploadedTmpName;
}
$nw = 125;
$nh = 90;
$source = $destFilePath;
$stype1 = explode('.', $source);
$stype = $stype1[count($stype1) - 1];
$dest = $_SERVER['DOCUMENT_ROOT'].'/upload/thumb/'.$destFilename.$sExt;
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
compress($source, "$desired_dir/".$file_name, 50);
$uploadedFiles[] = $destFilePath;
}
$stmt = $conn->prepare('INSERT INTO allpostdata(im1, im2, im3, im4)'
.' VALUES (?, ?, ?, ?)');
if ($stmt->execute($uploadedFiles)) {
header('Location: /post/price_plan.php');
}
}
exit;
}

Not a valid PNG file

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!

How to upload a image to directory

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

how to resize the uploading image and moving to a folder

i am trying to re size the uploading image and moving to a folder, i try with the blow code, but it is not work. i created a function for re sizing the photo, calling that function from another function, but image is not re sized, and photo is not moved to folder.
$final_save_dir = 'techpic';
$thumbname = $_FILES['tpic']['name'];
$imgName = $final_save_dir . '/' . $_FILES['tpic']['name'];
if(#move_uploaded_file($_FILES['tpic']['tmp_name'], $final_save_dir . '/' . $_FILES['tpic']['name']))
{
$this->createThumbnail($thumbname,"600","600",$final_save_dir,$final_save_dir);
}
function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $image_name;
$mime = getimagesize($path);
if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if($old_x > $old_y)
{
$thumb_w = $new_width;
$thumb_h = $old_y*($new_height/$old_x);
}
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
if($old_x == $old_y)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// New save location
$new_thumb_loc = $moveToDir . $image_name;
if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
function img($field = 'image', $width = null, $height = null, $crop = false, $alt = null, $turl = null) {
global $editormode;
$val = $field;
if (!$val)
$val = 'no-image.png';
$alt = ($alt) ? $alt : stem(basename($val));
if ($width == null && $height == null)
$imgf = get_dir() . $val;
else
$imgf = gen_img($val, $width, $height, $crop);
if (!$imgf)
return "";
$url = $imgf;
if (!$turl)
return "<img src='$url' alt='$alt'/>\n";
else
return "<a href='$turl'><img src='$url' alt='$alt'/></a>";
}
function get_dir() {
return "upload/";
}
function gen_img($fileval, $width, $height, $crop) {
if (!$fileval)
return null;
$fname = get_dir() . $fileval;
if (!is_readable($fname))
return null;
$stem = stem(basename($fname));
if ($width != null && $height != null) {
$sz = getimagesize($fname);
if ($sz[0] == $width && $sz[1] == $height) {
return substr($fname, strlen(UPLOADROOT));
}
$sep = ($crop) ? '__' : '_';
$outname = thumb_dir($fname) . $stem . $sep . $width . "x" . $height . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $height, $crop);
}
else if ($width != null && $height == null) {
$outname = thumb_dir($fname) . $stem . "_" . $width . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $crop);
} else
$outname = $fname;
//echo $outname; die();
return $outname;
}
function thumb_dir($path) {
$enddir = strrpos($path, "/");
$dir = substr($path, 0, $enddir) . "/.thumbnails/";
if (!file_exists($dir))
mkdir($dir, 0777, true);
return $dir;
}
function createthumb($source, $dest, $new_w, $new_h = null, $crop = false) {
if (!file_exists($source))
return null;
$src_img = 0;
$src_img = image_create($source);
$old_w = imageSX($src_img);
$old_h = imageSY($src_img);
$x = $y = 0;
if ($new_h == null) { // we want a square thumb, cropped if necessary
if ($old_w > $old_h) {
$x = ceil(($old_w - $old_h) / 2);
$old_w = $old_h;
} else if ($old_h > $old_w) {
$y = ceil(($old_h - $old_w) / 2);
$old_h = $old_w;
}
$thumb_w = $thumb_h = $new_w;
} else if ($crop) {
$thumb_w = $new_w;
$thumb_h = $new_h;
$oar = $old_w / $old_h;
$nar = $new_w / $new_h;
if ($oar < $nar) {
$y = ($old_h - $old_h * $oar / $nar) / 2;
$old_h = ($old_h * $oar / $nar);
} else {
$x = ($old_w - $old_w * $nar / $oar) / 2;
$old_w = ($old_w * $nar / $oar);
}
} else if ($new_w * $old_h / $old_w <= $new_h) { // retain aspect ratio, limit by new_w
$thumb_h = $new_w * $old_h / $old_w;
$thumb_w = $new_w;
} else { // retain aspect ratio, limit by new_h
$thumb_w = $new_h * $old_w / $old_h;
$thumb_h = $new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecolortransparent($dst_img, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $thumb_w, $thumb_h, $old_w, $old_h);
image_save($dst_img, $dest);
imagedestroy($dst_img);
imagedestroy($src_img);
}
function image_create($source) {
$suf = strtolower(suffix($source));
if ($source == '.jpg')
mylog("wtf", "source: $source", true);
if ($suf == "png")
return imagecreatefrompng($source);
else if ($suf == "jpg" || $suf == "jpeg")
return imagecreatefromjpeg($source);
else if ($suf == "gif")
return imagecreatefromgif($source);
return null;
}
function image_save($dst_img, $dest) {
$suf = strtolower(suffix($dest));
if ($suf == "png")
imagepng($dst_img, $dest);
else if ($suf == "jpg" || $suf == "jpeg")
imagejpeg($dst_img, $dest);
else if ($suf == "gif")
imagegif($dst_img, $dest);
}
This your function which is put in your function file
that function has make Folder in the thumbnails in the image folder when you call the function file.
Following way to call the function when image display.
<?php echo img('pages/sample_image.jpg', 122, 81, TRUE) ?>
Here the first is path of the image and 122:means width and 81:height and True/false True:crop the image and false: only resize the image.
And define the Uploadroot in your config file this path for the image folder.
Hope this works.
Thanks.
For resizing an image in php you can use Imagick::resizeImage from this article or use this article
Of course we can use Gd library which has low overhead by recommendation of #CD001. You can find explanation of GD re sizing in this article
Edit for More Explanation
for using Imagick::resizeImage you should see this description
here is the prototype of the function:
bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
Parameters
columns
Width of the image
rows
Height of the image
filter
Refer to the list of filter constants.
blur
The blur factor where > 1 is blurry, < 1 is sharp.
bestfit
Optional fit parameter.
If you want to use gd library here is simple source code
<?php
// File and new size
//the original image has 800x600
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// 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);
imagedestroy($thumb);

Image doesn't display

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

Categories