Cannot get new image size PHP - php

I am trying to get filesize of images from a specific folder AFTER and BEFORE they are optimized.
I get same size for $imgsize as well as $newsize even though the latter appears AFTER they images are optimized. What i actually want is that it gets me the NEW size, not the old!
$array has the list of URLs for images (absolute URLs, belongs to another server)
(also let me know, is this fine that i'm replacing the same image after optimizing size in this part $optimized_image= compress_image($path, $path, 50); ) ?
Here is my code:
$f_path='newfolder';
foreach ($array as $imglink)
{
$image = file_get_contents($imglink);
$path= $f_path . "/" . basename($imglink);
$new_image=file_put_contents($path , $image);
$imgsize = filesize($path);
$optimized_image= compress_image($path, $path, 50);
$newsize = filesize($path);
$percentage = ($imgsize / $newsize)*100;
echo $imgsize . "<br/>"; //this size appears fine
echo $newsize; //gives same size as above, no change!
}
And here is the function i'm using for compressing image (which seem to work perfectly fine to me)
function compress_image($src, $dest , $quality)
{
$info = getimagesize($src);
if ($info['mime'] == 'image/jpeg')
{
$image = imagecreatefromjpeg($src);
}
elseif ($info['mime'] == 'image/gif')
{
$image = imagecreatefromgif($src);
}
elseif ($info['mime'] == 'image/png')
{
$image = imagecreatefrompng($src);
}
else
{
die('uknown format');
}
imagejpeg($image, $dest, $quality);
}

Thanks to #u_mulder for the answer. The clearstatcache worked perfectly and solved the problem! :) This is because it deletes the old variable data.

Related

Compress image with PHP not reducing image size

I'm trying to compress and upload an image to the server with PHP. The upload are working correctly (without any errors), however the image size remains the same after the upload has completed. Could someone please advise what I could possibly be doing wrong?
Please find the code below:
public function addcoverimageAction()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize POST array
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$userid = $this->route_params['userid'];
$thisuser = $userid;
$postid = $this->route_params['postid'];
$path_parts = pathinfo($_FILES['file']['name']);
$filename = $path_parts['filename'] . '_' . microtime(true) . '.' . $path_parts['extension'];
$directoryName = dirname(__DIR__) . "/images/$thisuser/listings/$postid/coverimage/";
// Check if directory exist
if (!is_dir($directoryName)) {
//If directory does net exist - create directory
mkdir($directoryName, 0777, true);
}
// Compress image
function compressImage($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
}
compressImage($_FILES['file']['tmp_name'], $directoryName . $filename, 60);
// Upload image
move_uploaded_file($_FILES['file']['tmp_name'], $directoryName . $filename);
}
$this->post = Post::findByID($postid);
Post::updateCoverimage($filename, $postid);
}
If it is working, then you're immediately overwriting the compressed file with the original, via the move_uploaded_file command, because you're sending it to the same destination as the compressed file, which was an earlier step.
The move_uploaded_file command is unnecessary in this case - you can remove it

Php corrupted image upload

I have a photo upload area. it was working without any problems. But then I started to notice that it didn't upload some images. in others, colors and pixels began to appear incorrect. No problems with old files. only some of the new uploads.
This problem started to occur on its own without any changes in my codes.
I'm cropping a photo using cropper js.
not every upload is like this. I leave the interesting examples here.
sometimes it doesn't load the image at all.
How can something that works properly fail by itself?
sorry my bad english. thanks in advance to everyone who helped
$file = $_FILES['avatar'];
$fileName = $_FILES['avatar']['name'];
$fileTmpName = $_FILES['avatar']['tmp_name'];
$fileError = $_FILES['avatar']['error'];
$fileSize = $_FILES['avatar']['size'];
$fileType = $_FILES['avatar']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
if($fileError === 0){
if($fileSize < 100000000){
$fileNameNew = time().md5(time().$o_id.$fileName)."_".sha1($user_id.rand(10,99)).$l_category.".".$fileActualExt;
$fileDestination = "photos/".$fileNameNew;
function compressImage($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 true;
}
compressImage($fileTmpName, $fileDestination, 90);
}
I would check if these are filetype related or not. First and last one could be paletted PNG with shifted or partially applied/recognised palette.
The middle one should be a processing error as it has a visible split of contrast in the upper part.
Should be sort of autoexposure that is running on them and fails to do it's job well?
I would say this isn't upload or file error as that'll cause the file to be roken totally 'after' the error and most likely GD won't do a getimagesize() on them nor can use those files.
Also some PHP-related hints:
The pathinfo() is used to get the 'last' extension.
$fileActualExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
That imagecreatefrom* is pain in the ass, but you can use a helper to make it better, also you should use the getimagesize(), imagejpeg() and iamgecreatefrom*() return values for checking if they were really okay.
function getGDImage($source) {
if (!($info = getimagesize($source))) {
return false;
}
switch($info['mime']) {
case 'image/jpeg': return imagecreatefromjpeg($source);
case 'image/gif': return imagecreatefromgif($source);
case 'image/png': return imagecreatefrompng($source);
default: return false;
}
}
function compressImage($source, $destination, $quality) {
return ($image = getGDImage($source))
? imagejpeg($image, $destination, $quality)
: false;
}

Compress & resize images using PHP GD lib not working for png and weird results for jpg

I am trying to compress & resize my images using the php GD library. Nearly every answer on SO and everywhere else is the same, but for my solution, the PNG's are not being correctly transformed, and some jpg's are giving bizarre results.
This is the code I am using:
public function resizeImages() {
ini_set('max_execution_time', 0);
//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = FCPATH . 'design/img/test/'; //Source Image Directory End with Slash
$DestImagesDirectory = FCPATH . 'design/img/test/thumb/'; //Destination Image Directory End with Slash
$NewImageWidth = 150; //New Width of Image
$NewImageHeight = 150; // New Height of Image
$Quality = 90; //Image Quality
//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImagesDirectory)){
while(($file = readdir($dir))!== false){
$imagePath = $ImagesDirectory.$file;
$destPath = $DestImagesDirectory.$file;
$checkValidImage = #getimagesize($imagePath);
if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
{
//Image looks valid, resize.
if (resize_image($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality))
{
echo $file.' resize Success!<br />';
/*
Now Image is resized, may be save information in database?
*/
} else {
echo $file.' resize Failed!<br />';
}
}
}
closedir($dir);
}
}
and the resize_image function looks like this:
function resize_image($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
list($iWidth,$iHeight,$type) = getimagesize($SrcImage);
$ImageScale = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
$NewWidth = ceil($ImageScale*$iWidth);
$NewHeight = ceil($ImageScale*$iHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
$imagetype = strtolower(image_type_to_mime_type($type));
switch($imagetype)
{
case 'image/jpeg':
$NewImage = imagecreatefromjpeg($SrcImage);
break;
case 'image/png':
$NewImage = imagecreatefrompng($SrcImage);
break;
default:
return false;
}
//allow transparency for pngs
imagealphablending($NewCanves, false);
imagesavealpha($NewCanves, true);
// Resize Image
if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
switch ($imagetype) {
case 'image/jpeg':
if(imagejpeg($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
case 'image/png':
if(imagepng($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
default:
return false;
}
return true;
}
}
Every single png is not working, it just returns a file with 0 bytes and "file type is not supported", even though the type is recognized as .PNG in Windows...
Some JPG's return a weird result as well, see the following screenshot which indicates my issues regarding png's and some jpg's:
1) Do not use getimagesize to verify that the file is a valid image, to mention the manual:
Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.
$checkValidImage = exif_imagetype($imagePath);
if(file_exists($imagePath) && ($checkValidImage == IMAGETYPE_JPEG || $checkValidImage == IMAGETYPE_PNG))
2) While imagejpeg() accepts quality from 0 to 100, imagepng() wants values between 0 and 9, you could do something like that:
if(imagepng($NewCanves,$DestImage,round(($Quality/100)*9)))
3) Using readdir () you should skip the current directory . and the parent..
while(($file = readdir($dir))!== false){
if ($file == "." || $file == "..")
continue;
edit
Point 2 is particularly important, imagepng () accepts values greater than 9 but then often fails with error in zlib or libpng generating corrupt png files.
I tried resizing some png and jpeg and I didn't encounter any problems with these changes.

How to fix: Notice: Array to string conversion error when I try to compress images based on an array

Hi I need help with my code please. I was trying to compress images on an array but I received an error called "Notice: Array to string conversion" and I don't know how tho solve it I guess that the var $location could be the problem...
I attached my code and the problematic line is:
$location = $carpeta.$_FILES['imagen']['name'];
<?php
/*CREATE A FOLDER TO INSERT THE IMAGES*/
$carpeta = "../img/posts/".$tipo_post."/".$fecha_post." - ".$encabezado_post."/";
$carpeta_bd = "img/posts/".$tipo_post."/".$fecha_post." - ".$encabezado_post."/";
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
/*IT'S TIME TO INSERT THE IMAGES*/
$imagenes_a_contar = $_FILES['imagen']['name']; //COUNTING IMAGES
$contador_imagenes = count($imagenes_a_contar);
for ($i = 0; $i < ($contador_imagenes); ++$i) {
$nombre_imagen_normal = $_FILES["imagen"]["name"];
$nombre_imagen_tmp = $_FILES["imagen"]["tmp_name"];
/*TRYING TO COMPRESS THE IMAGES BEFORE TO SAVE THEM*/
$valid_ext = array('png', 'jpeg', 'jpg');
$location = $carpeta.$_FILES['imagen']['name'];
// GET THE FILE EXTENSION
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// CHECK THE EXTENSION TO START THE COMPRESSION
if (in_array($file_extension, $valid_ext)) {
$location_2 = $carpeta.$_FILES['imagen']['name'].$file_extension;
// COMPRESSING IMAGES
compressImage($_FILES["imagen"]["name"], $location_2, 60);
}
/*SAVING IMAGES INTO THE DIRECTORY AND THE DATABASE*/
//$url_imagen_normal[$i] = $carpeta.$nombre_imagen_normal[$i];
$url_imagen_bd[$i] = $carpeta_bd.$nombre_imagen_normal[$i];
#copy($nombre_imagen_tmp[$i], $url_imagen_normal[$i]);
mysqli_query($conexion_post, "INSERT INTO imagenes VALUES('','$codigo_post','$url_imagen_bd[$i]','1')");
}
/*-------------------------------------*/
/*FUNCTION TO COMPRESS IMAGES*/
function compressImage($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);
}
Thanks in advance.

Reduce image quality in php

How can I reduce the quality of an image using PHP ?
upload_mode = #$this->setting->upload_mode?:'file';
$upload_path = #$this->setting->upload_path?:'uploads/';
$file = Request::file($name);
$fm = array();
$fm['name'] = $_FILES[$name]['name'];
$fm['ext'] = $file->getClientOriginalExtension();
$fm['size'] = $_FILES[$name]['size'];
$fm['content_type'] = $_FILES[$name]['type'];
if($upload_mode=='database') {
$fm['filedata'] = file_get_contents($_FILES[$name]['tmp_name']);
DB::table('cms_filemanager')->insert($fm);
$id_fm = DB::getPdo()->lastInsertId();
DB::table('cms_filemanager')->where('id',$id_fm)->update(['id_md5' =>md5($id_fm)]);
$filename = 'upload_virtual/files/'.md5($id_fm).'.'.$fm['ext'];
}else{
if(!file_exists($upload_path.date('Y-m'))) {
if(!mkdir($upload_path.date('Y-m'),0777)) {
die('Gagal buat folder '.$upload_path.date('Y-m'));
}
}
$filename = md5(str_random(12)).'.'.$fm['ext'];
$file->move($upload_path.date('Y-m'),$filename);
$filename = $upload_path.date('Y-m').'/'.$filename;
}
$url = asset($filename);
have someone help me ? what i need add to make it work like what i need ?
GD is an open source code library for the dynamic creation of images
by programmers. GD is written in C, and "wrappers" are available for
Perl, PHP and other languages. GD creates PNG, JPEG and GIF images,
among other formats. GD is commonly used to generate charts, graphics,
thumbnails, and most anything else, on the fly.
Code to reduce file size for the image:
<?php
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;
}
$source_img = 'source.jpg';
$destination_img = 'destination .jpg';
$d = compress($source_img, $destination_img, 90);
?>
$d = compress($source_img, $destination_img, 90);
Reference

Categories