PHP script is not resizing image - php

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

Related

resize bulk of images on 1280x 720 without cropping

I have 60 jpg images inside img folder
they are all of various dimensions
need all of them to be 1280 x 720
white background - if needed
using this code spinner on page works obut 10 seconds - meaning the code works something - but final result is - nothing
each image has the same dimension as before
pls help
function resize_no_crop($el, $w, $h) {
list($width, $height) = getimagesize($el);
$r = $width / $height;
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
$src = imagecreatefromjpeg($el);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
$arr = glob('img/*');
foreach($arr as $el){resize_no_crop($el, 1280, 720);}
echo 'finito';
You aren't saving the images:
$quality = 95;
foreach($arr as $el){
// Destinazione
$dest = dirname($el).DIRECTORY_SEPARATOR.basename($el, '.jpg') . '.cropped.jpg';
$resized = resize_no_crop($el, 1280, 720);
imagejpeg($resized, $dest, $quality);
}
Or you cal use $dest = $el to overwrite the original images (I never recommend this).
Use Imagick resizeImage:
foreach($arr as $el) {
$im = new \Imagick();
$im->readImage($el);
$im->resizeImage(1280, 720, \Imagick::FILTER_BOX, 1);
$im->writeImage($el);
$im->destroy();
}
From documentation: https://www.php.net/manual/en/imagick.resizeimage.php

PHP image upload with watermark

I have this code which uploads images with watermarks. The code works fine but the watermark function re-resizes all the images upload to small width and height. I want to retain the size after adding the watermark. I believe the problem is in function but I don't know how to fix it.
if(isset($_FILES)){
$file = $_FILES['image'];
$allowedExts = array('jpg','png','gif','jpeg');
$uploadsDirectory = "imgupload/";
$maxSize = 2000000;
for($i = 0; $i < count($file['name']); $i++){
$filetmpname = $file['tmp_name'][$i];
$errors = array();
$filename = $file['name'][$i];
$filetext = strtolower(end(explode('.',$filename)));
$filesize = $file['size'][$i];
$filetmpname = $file['tmp_name'][$i];
if(in_array($filetext, $allowedExts) === FALSE){
$errors[] = "Extension is not allowed";
}
if($filesize > $maxSize){
$errors[] = "File Size must be less than {$maxSize} KB";
}
if(empty($errors)){
$random = rand(0,199);
$destination = $file['name'][$i] = $uploadsDirectory. $random."_".date("d-m-Y") . "_" . $file['name'][$i];
$upload_status = move_uploaded_file($filetmpname, $destination);
if($upload_status){
$new_name = $uploadsDirectory.$random."_".date("d-m-Y") . "_" .".jpg";
if(watermark_image($destination, $new_name))
$demo_image = $new_name;
}
}
}
}
Watermark Function:
$image_path = "images/water.png";
function watermark_image($oldimage_name, $new_image_name)
{
global $image_path;
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = $height = 300;
$im = imagecreatetruecolor($width, $height);
$img_src = imagecreatefromjpeg($oldimage_name);
imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
$watermark = imagecreatefrompng($image_path);
list($w_width, $w_height) = getimagesize($image_path);
$pos_x = $width - $w_width;
$pos_y = $height - $w_height;
imagecopy($im, $watermark, $pos_x, $pos_y, 0, 0, $w_width, $w_height);
imagejpeg($im, $new_image_name, 100);
imagedestroy($im);
unlink($oldimage_name);
return true;
}
You are getting the size of the existing image here:
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = $height = 300;
This is where it is making the different size image:
imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
http://php.net/manual/en/function.imagecopyresampled.php

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

How to resize image in this PHP script?

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.

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