How to resize image in this PHP script? - php

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.

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

Saving Image with the actual scale gotten from image cropping tool

I am trying to save image the same way it look on cropping tool, using the coping i got something like this X = 443 and Y = 180 and Width = 180 and height = 180, now my problem is how to send it to php to resize the original image as the image editor showed using the above information. Currently am using the below php code to resize image with and height but to add X and Y is what has been giving me problem.
<?php
function CroppedThumbnail($imagename, $path, $width, $height, $rename, $imgQuality, $ratio=false){
$url = '';
$info = pathinfo($imagename);
$newpath = $path;
$cdn_newpath = 'cdn/';
//Rename the image
if($rename == true){ $newFileName = $newpath . '/' . substr($info['filename'],0,5) . '-' . $width . 'x' . $height . '.jpeg';}
else{ $newFileName = $newpath . '/' . $imagename;}
$imageAvatar = substr($info['filename'],0,5) . '-' . $width . 'x' . $height . '.jpeg';
if(!file_exists($cdn_newpath.$newpath)){
mkdir($cdn_newpath.$newpath, 0777, true);
chmod($cdn_newpath.$newpath, 0755);
}
if(is_dir($cdn_newpath.$newpath . '/') && file_exists($cdn_newpath.$newFileName)){ return $url . $newFileName;}
else{
// Resample
if ($info['extension'] == 'jpeg' OR $info['extension'] == 'jpg'){ $image = imagecreatefromjpeg($imagename);}
else if ($info['extension'] == 'gif'){ $image = imagecreatefromgif($imagename);}
else if ($info['extension'] == 'png'){ $image = imagecreatefrompng($imagename);}
$widthx = imagesx( $image );
$heighty = imagesy( $image );
// calculate thumbnail size
if($ratio == true){
$new_width = $width;
$new_height = floor( $heighty * ( $width / $widthx ) );
$image_p = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $widthx, $heighty );
}else{
$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $widthx, $heighty);
}
imagejpeg($image_p, $cdn_newpath.$newFileName);
return $url . $newFileName;
}
}
?>
You are facing same problem as I had faced. See below code snippet which I have extracted from my class. Some of the code will look pseudo code to you.
$trueFactorx = $original_height/$current_height;
$trueFactory = $original_width/$current_width;
// calls to my wrapper functions
$img=image_crop($img,$crop_cordinates,$trueFactorx,$trueFactory);
save_image($img,$image_type,$new_image_path);
function image_crop($img1,$crop_cordinates,$factorX,$factorY)
{
$corrdinate_array=explode(",", $crop_cordinates);
$x=$corrdinate_array[0] * $factorX;
$y=$corrdinate_array[1]* $factorY;
$height=$corrdinate_array[2]* $factorY;
$width=$corrdinate_array[3]* $factorX;
$img2 = imagecreatetruecolor($width, $height);
imagecopy($img2, $img1, 0, 0, $x, $y, $width, $height);
return $img2;
}
function save_image($img,$image_type,$new_image_path)
{
switch(strtolower($image_type))
{
case 'png':
header( 'Content-Type: image/png' );
imagepng($img,$new_image_path);
break;
case 'gif':
imagegif($img,$new_image_path);
break;
case 'jpeg':
imagejpeg($img,$new_image_path);
break;
case 'jpg':
imagejpeg($img,$new_image_path);
break;
default:
die('Unsupported File!');
}
imagedestroy($img);
}
Good Luck!

PHP script is not resizing image

I have a method to resize image, that accepts image string and new dimensions and should return new image string. But it doesn't work
public function putBase64ThumbToFile($base64String){
$fs = new Filesystem();
$TEMP_FOLDER_NAME = "tmpimageupload";
$pos = strpos($base64String, ';');
$type = explode('/', substr($base64String, 0, $pos))[1];
$base64String = str_replace('data:image/'. $type .';base64,', '', $base64String);
$base64String = str_replace(' ', '+', $base64String);
$data = base64_decode($base64String);
$resizedImage = $this->resizeAndCompressImage($data, 100, 100);
$fs->mkdir($TEMP_FOLDER_NAME, 0700);
$tempFilePath = $TEMP_FOLDER_NAME.'/'.uniqid() . '.' . $type;
file_put_contents($tempFilePath, $resizedImage);
}
public function resizeAndCompressImage($data, $w, $h) {
list($width, $height) = getimagesizefromstring($data);
$r = $width / $height;
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
$src = imagecreatefromstring($data);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ob_start();
imagepng($src);
$image = ob_get_clean();
return $image;
}
In the result I get same unresized image.
You mistake is on this line:
imagepng($src);
you take the source image and not the destination image:
imagepng($dst);

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

Resize PNG image in PHP

I'm getting a no image display when resizing PNG however the following code works for JPEG.
list($width_orig, $height_orig) = getimagesize( $fileName );
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
if( $type )){
switch( $type ){
case 'image/jpeg':
$image = imagecreatefromjpeg($fileName);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, null, 100);
break;
case 'image/png':
imagealphablending( $image_p, false );
imagesavealpha( $image_p, true );
$image = imagecreatefrompng( $fileName );
imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagepng($image_p, null, 100);
break;
}
}
I've put the headers in but for some reason I'm doing something wrong for png images.
Last argument in imagepng($image_p, null, 100) should be between 0 and 9.
try this:
$image = imagecreatefrompng ( $filename );
$new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
imagealphablending($new_image , false);
imagesavealpha($new_image , true);
imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
$image = $new_image;
// saving
imagealphablending($image , false);
imagesavealpha($image , true);
imagepng ( $image, $filename );
see if this works
#upload de image
public function upImagem($imagem, $dir, $res, $id, $tam){
$arquivo = $imagem;
$arq_nome = $arquivo['name'];
$ext = $arquivo['type'];
$nome=$this->RenImg($arquivo, $dir, $id, $tam);
$imagem = $arquivo['tmp_name'];
if($ext=='image/jpeg'){
$img = imagecreatefromjpeg($imagem);
}
elseif($ext=='image/png'){
$img = imagecreatefrompng($imagem);
}
elseif($ext=='image/gif'){
$img = imagecreatefromgif($imagem);
}
if(($ext=='image/png') or ($ext=='image/gif')){
list($x, $y) = getimagesize($arquivo['tmp_name']);
}
elseif($ext=='image/jpeg'){
$x = imagesx($img);//original height
$y = imagesy($img);//original width
}
$altura = $res[1];
$largura = $res[0];
$nova = imagecreatetruecolor($largura,$altura);
$preto = imagecolorallocate($nova, 0, 0, 0);
if(($ext=='image/png') or ($ext=='image/gif')){
imagealphablending($nova , false);
imagesavealpha($nova , true);
}
if($ext=='image/png'){
imagecolortransparent ($nova, $preto);
imagecopymerge($img, $nova, 0, 0, 0, 0, imagesx($nova), imagesy($nova), 100);
imagecopyresized($nova,$img,0,0,0,0,$largura,$altura, $x, $y );
}
else {
imagecopyresampled($nova,$img,0,0,0,0,$largura,$altura,$x,$y);
}
if($ext=='image/jpeg'){
imagejpeg($nova,$nome,99);
}
elseif($ext=='image/gif'){
imagealphablending($nova , false);
imagesavealpha($nova , true);
imagegif($nova,$nome,99);
}
elseif($ext=='image/png'){
imagealphablending($nova , false);
imagesavealpha($nova , true);
imagepng($nova,$nome);
}
imagedestroy($img);
imagedestroy($nova);
}
#renames the image
public function RenImg($arq,$dir,$id,$tam){
$arq_nome = $arq['name'];
$arq_nome2=str_replace('.jpg','',$arq['name']);//renomeia o arquivo
$arq_nome2=str_replace('.png','',$arq_nome2);//renomeia o arquivo
$arq_nome2=str_replace('.gif','',$arq_nome2);//renomeia o arquivo
//$new_name = md5($arq_nome);
$ext = $this->getExt($arq_nome);
$nome = $dir.$id.$tam.'.jpg';//.'.'.$ext
return $nome;
}
#capture the file extension
public function getExt($arq){
$ext = pathinfo($arq, PATHINFO_EXTENSION);
return $ext;
}
This is a code i use for JPG/PNG rezise.
$imagename = "default";
if (isset ($_FILES['arquivo'])) {
$imagename = $imagename . ".jpg";
$source = $_FILES['arquivo']['tmp_name'];
$target = "images/tmp/" . $imagename;
$type = $_FILES["arquivo"]["type"];
//JPG or JPEG
if ($type == "image/jpeg" || $type == "image/jpg") {
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //Path to save the image
$file = "images/tmp/" . $imagepath; //path to orginal size image
list($width, $height) = getimagesize($file);
$modwidth = 1920;
$diff = $width / $modwidth; // Use $modheight = $idff to mantain aspect ratio
$modheight = 1080;
$tn = imagecreatetruecolor($modwidth, $modheight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
echo "<center><b><h5>Image was updated!</h5></b>";
imagejpeg($tn, $save, 100);
} elseif ($type == "image/png") { //PNG
move_uploaded_file($source, $target);
$imagepath = $imagename;
$save = "images/" . $imagepath; //Path to save the image
$file = "images/tmp/" . $imagepath; //path to orginal size image
list($width, $height) = getimagesize($file);
$modwidth = 1920;
$diff = $width / $modwidth; // Use $modheight = $idff to mantain aspect ratio
$modheight = 1080;
$tn = imagecreatetruecolor($modwidth, $modheight);
imagealphablending($tn, false);
imagesavealpha($tn, true);
$image = imagecreatefrompng($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
echo "Image was updated!";
imagepng($tn, $save, 9);
} else {
echo "Error!";
}
}

Categories