php resize image - php

I have a class to read and output the image content, if $width is set, it will resize the image, and then output it.
If I call the function like this $image->readImage('123.jpg'); , it can output the image file correctly, but when I call $image->readImage('123.jpg', 300); to resize it, it just display a black image with resized width & height.
And I tried to replace the code from
#imagejpeg($thumb, null, 100);
to
#imagejpeg($image, null, 100);
will works~
-
protected function readImage($fileName, $width = 0)
{
if ($width <= 0) {
return #file_get_contents($this->destination . '/' . $fileName);
} else {
$imageSize = #getimagesize($this->destination . '/' . $fileName);
$actualWidth = $imageSize[0];
$actualHeigth = $imageSize[1];
if ($actualWidth <= $width) {
return #file_get_contents($this->destination . '/' . $fileName);
}
$height = (100 / ($actualWidth / $width)) * .01;
$height = #round($actualHeigth * $height);
$image = #imagecreatefromjpeg($this->destination . '/' . $fileName);
$thumb = #imagecreatetruecolor($width, $height);
#imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $actualWidth, $actualHeight);
ob_start();
#imagejpeg($thumb, null, 100);
$bits = ob_get_contents();
ob_end_clean();
return $bits;
}
}
Any experts know what happened and help me to solve it ?
Thanks.

you've been inconsistant in your spelling of $actualHeight vs $actualHeigth
if you didn't have so many # everywhere, then php would have told you this.

Related

How to set aspect ratio in below code using PHP

I tried 2 implementations, shown below. Both are working well but when I tried to mix them it is not working anymore.
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_file_input']["error"] > 0) {
$output['error']= "File Error";
}
elseif (!in_array($_FILES['image_file_input']["type"], $allowedImageType)) {
$output['error']= "Invalid image format";
}
elseif (round($_FILES['image_file_input']["size"] / 1024) > 4096) {
$output['error']= "Maximum file upload size is exceeded";
} else {
$temp_path = $_FILES['image_file_input']['tmp_name'];
$file = pathinfo($_FILES['image_file_input']['name']);
$fileType = $file["extension"];
$photo_name = $productname.'-'.$member_id."_".time();
$fileName1 = $photo_name . '-125x125' . ".jpg";
$fileName2 = $photo_name . '-250x250' . ".jpg";
$fileName3 = $photo_name . '-500x500' . ".jpg";
$small_thumbnail_path = "uploads/large/";
createFolder($small_thumbnail_path);
$small_thumbnail = $small_thumbnail_path . $fileName1;
$medium_thumbnail_path = "uploads/large/";
createFolder($medium_thumbnail_path);
$medium_thumbnail = $medium_thumbnail_path . $fileName2;
$large_thumbnail_path = "uploads/large/";
createFolder($large_thumbnail_path);
$large_thumbnail = $large_thumbnail_path . $fileName3;
$thumb1 = createThumbnail($temp_path, $small_thumbnail,$fileType, 125, 125 );
$thumb2 = createThumbnail($temp_path, $medium_thumbnail, $fileType, 250, 250);
$thumb3 = createThumbnail($temp_path, $large_thumbnail,$fileType, 500, 500);
if($thumb1 && $thumb2 && $thumb3) {
$output['status']=TRUE;
$output['small']= $small_thumbnail;
$output['medium']= $medium_thumbnail;
$output['large']= $large_thumbnail;
}
}
echo json_encode($output);
Function File
function createFolder($path)
{
if (!file_exists($path)) {
mkdir($path, 0755, TRUE);
}
}
function createThumbnail($sourcePath, $targetPath, $file_type, $thumbWidth, $thumbHeight){
$source = imagecreatefromjpeg($sourcePath);
$width = imagesx($source);
$height = imagesy($source);
$tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
if (imagejpeg($tnumbImage, $targetPath, 90)) {
imagedestroy($tnumbImage);
imagedestroy($source);
return TRUE;
} else {
return FALSE;
}
}
Aspect ratio code, which is another one I tried to mix this code. But I was unsuccessful
$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
$photo_name = $productname.'-'.$member_id."_".time();
{
if( $ratio > 1) {
$width1 = 500;
$height1 = 500/$ratio;
}
else {
$width1 = 500*$ratio;
$height1 = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width1,$height1);
$fileName3 = $photo_name . '-500x500' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width1,$height1,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName3); // adjust format as needed
imagedestroy($dst);
if( $ratio > 1) {
$width2 = 250;
$height2 = 250/$ratio;
}
else {
$width2 = 250*$ratio;
$height2 = 250;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width2,$height2);
$fileName2 = $photo_name . '-250x250' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width2,$height2,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName2); // adjust format as needed
imagedestroy($dst);
}
What I need is to save my image after resizing but in second code there is no condition check, and I can't get image upload folder path. That's why I need to merge these 2 codes.
Basically I need need to save my image in 3 size formats: 500x500,250x250 and 125x125. Width is fixed, but height is set as per aspect ratio and set upload folder and condition in second code block.
Try this thumbnail function, which takes your source image resource and thumbnail size, and returns a new image resource for the thumbnail.
function createThumbnail($src, int $width = 100, int $height = null) {
// Ensure that src is a valid gd resource
if (!(is_resource($src) && 'gd' === get_resource_type($src))) {
throw new InvalidArgumentException(
sprintf("Argument 1 of %s expected type resource(gd), %s supplied", __FUNCTION__, gettype($src))
);
}
// Extract source image width, height and aspect ratio
$source_width = imagesx($src);
$source_height = imagesy($src);
$ratio = $source_width / $source_height;
// We know that width is always supplied, and that height can be null
// We must solve height according to aspect ratio if null is supplied
if (null === $height) {
$height = round($width / $ratio);
}
// Create the thumbnail resampled resource
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, $source_width, $source_height);
return $thumb;
}
Given your code above, you can now use the function like this
// Get uploaded file information as you have
// Create your source resource as you have
$source = imagecreatefromstring(file_get_contents($fn));
// Create thumbnails and save + destroy
$thumb = createThumbnail($source, 500);
imagejpeg($thumb, $thumb500TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 250);
imagejpeg($thumb, $thumb250TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 125);
imagejpeg($thumb, $thumb125TargetPath, 90);
imagedestroy($thumb);
// Don't forget to destroy the source resource
imagedestroy($source);

Error in create_thumbnail function

I am trying to upload an image using a form, everything so far in the form functions well except i get this error after i submit the form and the data gets submitted to the database table : **
Notice>: Undefined offset: 1 in D:\wamp\www\asserter\includes\create_thumbnail.php on line 40
this is the line 40 in the create_thumbnail() function : imagecopyresampled($thumb, $src, 0, 0, $src_pos[0], $src_pos[1], $new_size[0], $new_size[1], $size[0], $size[1]);
if comment the create_thumbnail() in my codes everything works fine and the image gets uploaded and i get no error back, but when i add create_thumbnail() line of code the original image does not get uploaded to the path but the thumbnail gets created and i still get this error ! please help !
here is my codes :
if ($_FILES["discussion_image"]["name"] != "") {
$test = explode(".", $_FILES["discussion_image"]["name"]);
$extension = end($test);
$name = rand(100, 9999999999);
$file_temp = $_FILES['discussion_image']['tmp_name'];
$file_path = '../uploaded_pictures/uploads/' . $user_id . '/'. $name .'.'.$extension;
//$file_path = mysqli_real_escape_string($connection, $file_path);
move_uploaded_file($file_temp, $file_path); // move_uploaded_file() is a built in function of PHP
$query = "INSERT INTO discussions_table (user_id, title, link, image_link, subject, discussion, discussion_timestamp) VALUES ($user_id, '$title', '$link', '$file_path', '$subject', '$discussion', $discussion_timestamp)";
$save_path = '../uploaded_pictures/uploads/' . $user_id . '/'. $name.'.jpg';
//$save_path_small = "../uploaded_pictures/uploads/" . $user_id . "/" . $name.'small.jpg';
create_thumbnail($file_path, $save_path, 250, 250); // creates thumbnail for profile picture
//create_thumbnail($file_path, $save_path_small, 50, 50); // creates thumbnail for small user picture
}
and here is my create_thumbnail function :
function create_thumbnail($path, $save, $width, $height) {
$info = getimagesize($path);
$size = array($info[0], $info[1]); // info[0] is the width and info[1] is the height
if ($info['mime'] == 'image/png') {
$src = imagecreatefrompng($path);
} else if ($info['mime'] == 'image/jpeg') {
$src = imagecreatefromjpeg($path);
} else {
return false;
}
$thumb = imagecreatetruecolor($width, $height);
$src_aspect = $size[0] / $size[1];
$thumb_aspect = $width / $height;
if ($src_aspect < $thumb_aspect) {
// means the image is narrower so we want to crop the top and bottom
$scale = $width / $size[0]; // width of the thumb and width of the actual image
$new_image = array($width, $width / $src_aspect);
$src_pos = array(0, ($size[1] * $scale - $height) / $scale / 2); // we are fixing x position to 0 and calculating the y position
} else if ($src_aspect > $thumb_aspect) {
// means image is wider so we need to crop left and right
$scale = $height / $size[1];
$new_size = array($height * $src_aspect, $height);
$src_pos = array(($size[0] * $scale - $width) / $scale / 2); // we are fixing y position to 0 and calculating the x position
} else {
// this means it is the same shape as the thumbnail we are creating
$new_size = array($width, $height);
$src_pos = array(0, 0);
}
$new_size[0] = max($new_size[0], 1);
$new_size[1] = max($new_size[1], 1);
imagecopyresampled($thumb, $src, 0, 0, $src_pos[0], $src_pos[1], $new_size[0], $new_size[1], $size[0], $size[1]);
if ($save === false) {
return imagejpeg($thumb);
} else {
return imagejpeg($thumb, $save);
}
}
Thanks everyone for your help, I found the bug !
it was a naming issue, i should replace this $new_image = array($width, $width / $src_aspect); with this $new_size = array($width, $width / $src_aspect);

Php image resampling dimension issue

Please i am using the below php image function to resize image when uploading or while displaying the image on page, but i found out that when i tried to resize an original image it doesn't give me the actual dimension that i want.
Example: the original image width is 600 and height is 400
I intend to resize it to 180 X 180, but it gave me width 180 and height 120. Please i don't know what the problem is can anyone help?
<?php
function CroppedThumbnail($imagename, $meta, $newpath, $imgwidth, $imgheight, $rename, $imgQuality){
// Set a maximum height and width
$width = $imgwidth;
$height = $imgheight;
$url = '';
//Get image info
$info = #getimagesize($imagename);
$fileparts = pathinfo($imagename);
// Get new dimensions
$imageAvatar = substr($fileparts['filename'],0,5) . '-' . $imgwidth . 'x' . $imgheight . '.png';
if(is_dir($newpath . '/') && file_exists($newpath . '/' . $imageAvatar)){
return $url . $newpath . '/' . $imageAvatar;
}else{
list($width_orig, $height_orig) = $info;
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
if ($info['mime'] == 'image/jpeg'){
$image = imagecreatefromjpeg($url.$imagename);
}
else if ($info['mime'] == 'image/gif'){
$image = imagecreatefromgif($url.$imagename);
}
else if ($info['mime'] == 'image/png'){
$image = imagecreatefrompng($url.$imagename);
}
$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
//Rename the image
if($rename == true){
$newName = substr($fileparts['filename'],0,5) . '-' . $imgwidth . 'x' . $imgheight;
$newFileName = $newpath . '/' . $newName . '.png';
}else{
$newFileName = $newpath . '/' . $imagename;
}
// Output
imagejpeg($image_p, $newFileName, $imgQuality);
return $url . $newFileName;
}
}
This because you are keeping the original aspect ratio of the image.
This is in the following line of code:
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
If you don't want to keep the aspect ration just delete those lines.

How to trim image with php?

This is my index.php file, i have uploaded and moved image from tmp folder to image folder and it's working properly. but now i want to trim image on display, every picture should be display of same size, i have tried lots of way but it's not working.
Need for help!!
<?php
require_once('appvars.php');
include 'db_connect.php';
$sql = "SELECT * FROM gitarwar";
$data = mysqli_query($dbc, $sql);
echo "<table>";
while ($row = mysqli_fetch_array($data))
{
echo '<tr><td>';
echo '<strong>' . $row['Score'] . '</strong><br/>';
echo '<strong>Name:</strong>' . $row['Name'] . '<br/>';
echo '<strong>Datetime:</strong>' . $row['Datetime'] . '<br/>';
echo '<img src="' .GW_UPLOADPATH . $row['Screenshot'] . '" alt="Score image" />';
echo "</tr>";
}
echo"</table>";
mysqli_close($dbc);
?>
I had a similar task before. My job was to check the image, and if it is smaller than my $newWidth or $newHeight, it added.
$imageUrl = [PATH OR URL TO YOUR IMAGE FILE];
$imageContent = file_get_contents($imageUrl);
$im = imagecreatefromstring($imageContent);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = 300;
$newheight = 300;
$output = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($output, false);
$transparency = imagecolorallocatealpha($output, 0, 0, 0, 127);
imagefill($output, 0, 0, $transparency);
imagesavealpha($output, true);
imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);
//Show the image
header('Content-Type: image/png');
imagepng($output); //You can save it with another parameter what is a path
imagedestroy($output);
imagedestroy($im);
You need to change this line:
imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);
to your size.
It's actually not exactly what you want, but it could be a good starting point.
You can trim the image when uploading it, by using imagecreatefrom(jpeg|png|gif) function.
$file = "images/" . $_FILES['image']['name'];
$tmp_file = $_FILES['image']['tmp_name'];
$type = $_FILES['images']['type'];
if (move_uploaded_file($tmp_file, $file)) {
chmod($file, 0777);
// check the type of image, you can do this for other types too, just change the imagecreatefrom function to the type you want to save the image as
if ($type === 'image/jpeg') {
$jpeg = imagecreatefromjpeg($file);
$jpeg_width = imagesx($jpeg);
$jpeg_height = imagesy($jpeg);
$new_width = imagesx($jpeg) / 4; // Fix the width of the thumb nail images, change the width of image here
$new_height = imagesy($jpeg) / 4; // change the height of image here
//new image
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $jpeg, 0, 0, 0, 0, $new_width, $new_height, $jpeg_width, $jpeg_height);
imagejpeg($new_image, $thumb);
chmod($thumb, 0777);
}
}

Compress & save base64 image

My app is receiving base64-encoded image-files from the webbrowser. I need to save them on the client. So I did:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
Which works fine.
Now I need to compress & resize the image to max. 800 width & height, maintaining the aspect-ratio.
So I tried:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
which does not work (error: "imagejpeg() expects parameter 1 to be resource, string given").
And of course, this does compress, but not resize.
Would it be best to save the file in /tmp, read it and resize/move via GD?
Thanks.
2nd part
Thanks to #ontrack I know now that
$data = imagejpeg(imagecreatefromstring($data),$uploadPath . $fileName,80);
works.
But now I need to resize the image to max 800 width and height. I have this function:
function resizeAndCompressImagefunction($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;
}
So I thought I could do:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
which does not work.
You can use imagecreatefromstring
To answer the second part:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
$data will only contain either true or false to indicate wether the operation of imagejpeg was a success. The bytes are in $uploadPath . $fileName. If you want the actual bytes back in $data you have to use a temporary output buffer:
$img = imagecreatefromstring($data);
$img = resizeAndCompressImagefunction($img, 800, 800);
ob_start();
imagejpeg($img, null, 80);
$data = ob_get_clean();

Categories