How to move compressed image file PHP - php

Here is the function that compress image file.
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg'){
$image = imagecreatefromjpeg($source_url);
}elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source_url);
}elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source_url);
}imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
$filename = compress_image($_FILES["home_image"]["tmp_name"], $_FILES["home_image"]["name"], 80);
$buffer = file_get_contents($_FILES["home_image"]["name"]);
Here is my code that want to move the compressed image to my specific folder
move_uploaded_file($_FILES["home_image"]["tmp_name"][$i],"../../../Test/image/home_banner/" .$filename);
But the image that move to the folder is still remain the original size without compress.
Am I doing the mistake..?

I think move_uplodaded_file() is not appropriate here, because you change the uploaded file contents:
This function checks to ensure that the file designated by filename is
a valid upload file (meaning that it was uploaded via PHP's HTTP POST
upload mechanism). If the file is valid, it will be moved to the
filename given by destination.
Use rename() instead.
I'm also not 100% if you can edit the uploaded file directly..

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

How to compress image file size laravel

I have some images in my S3 bucket on AWS. I am trying to get the images and send them to my android app (along with other information from my database). My current setup works fine but I would like to reduce the image file sizes (currently around 1-1.5mb) before I send them to the app.
I have tried to use this code:
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;
}
$image_file = Storage::disk('s3_upload')->get("s3bucketpath");
$new_image_file = $this->replace_extension($image->filename, '.jpg');
$this->compress($image_file,$new_image_file, 50);
I get
failed to open stream: No such file or directory in file
error from
$info = getimagesize($source);
I have checked the file path and it is in the bucket and exists and I have var-dumped source and gotten
����JFIF��C$<'$!!$J58,<XM\[VMUSam�vag�hSUy�z������^t�����������C$ $G''G�dUd����������������������������������������������������#0"����A!1A"Q2aq#B���3R�$4b�rC���%S���5D�����#!1A2"Q#��?��HS-�  B�#)( #�
#!#������(��(� �
#�UF�LHU#�d ��
# �)#RB�(R�E]��(
(� #B'...
What is the best way to go about doing this.
Try http://image.intervention.io/ to compress file.
It is simple and efficient.
Compression details:
http://image.intervention.io/api/encode
How to start? Simply:
// include composer autoload
require 'vendor/autoload.php';
// import the Intervention Image Manager Class
use Intervention\Image\ImageManager;
// create an image manager instance with favored driver
$manager = new ImageManager(array('driver' => 'imagick'));
// to finally create image instances
$image = $manager->make('public/foo.jpg')->resize(300, 200);
If you are really serious about compressing and resizing your images, you can use libraries like PNGQuant for PNG compression without losing the quality and jpegoptim for jpeg images.

Cannot get new image size 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.

Optimize uploaded images with php (jpeg)

When running Page Speed in Google Chrome it suggests to optimize/compress the images. These images are mostly uploaded by users, so I would need to optimize them during uploading. What I find about optimizing jpeg images with php is something like using the following GD functions:
getimagesize()
imagecreatefromjpeg()
imagejpeg()
Since I am resizing the images after upload I'm already pulling the image through these functions and in addition I use imagecopyresampled() after imagecreatefromjpeg() to resize it.
But then, Page Speed is still telling me these images can be optimized. How can I accomplish this optimisation in a php script? Set the quality lower in imagejpeg() doesn't make a difference either.
The imagejpeg function is where you assign the quality. If you're already setting that to an appropriate value then there is little else you can do.
Page speed probably considers all images above a certain size to be "needing compression", perhaps just ensure they are all as small as reasonable (in terms of height/width) and compressed.
You can find more about page speed and it's compression suggestions on the pagespeed docs http://code.google.com/speed/page-speed/docs/payload.html#CompressImages which describes some of the techniques/tools to compress appropriately.
I've also just read the following:
Several tools are available that perform further, lossless compression on JPEG and PNG files, with no effect on image quality. For JPEG, we recommend jpegtran or jpegoptim (available on Linux only; run with the --strip-all option). For PNG, we recommend OptiPNG or PNGOUT.
So perhaps (if you really want to stick to Google's suggestions) you could use PHP's exec to run one of those tools on files as they are uploaded.
To compress with php you do the following (sounds like you are already doing this):
Where $source_url is the image, $destination_url is where to save and $quality is a number between 1 and 100 choosing how much jpeg compression to use.
function compressImage($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
//save file
imagejpeg($image, $destination_url, $quality);
//return destination file
return $destination_url;
}
Repaired function:
function compressImage($source_url, $destination_url, $quality) {
//$quality :: 0 - 100
if( $destination_url == NULL || $destination_url == "" ) $destination_url = $source_url;
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg')
{
$image = imagecreatefromjpeg($source_url);
//save file
//ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
imagejpeg($image, $destination_url, $quality);
//Free up memory
imagedestroy($image);
}
elseif ($info['mime'] == 'image/png')
{
$image = imagecreatefrompng($source_url);
imageAlphaBlending($image, true);
imageSaveAlpha($image, true);
/* chang to png quality */
$png_quality = 9 - round(($quality / 100 ) * 9 );
imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression).
//Free up memory
imagedestroy($image);
}else
return FALSE;
return $destination_url;
}
You could use Imagick class for this. Consider following wrapper function:
<?php
function resizeImage($imagePath, $width, $height, $blur, $filterType = Imagick::FILTER_LANCZOS, $bestFit = false)
{
//The blur factor where > 1 is blurry, < 1 is sharp.
$img= new \Imagick(realpath($imagePath));
$img->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(40);
$img->stripImage();
$img->resizeImage($width, $height, $filterType, $blur, $bestFit);
$img->writeImage();
}
?>
Read more on how to resize images with Imagick at:
http://php.net/manual/en/class.imagick.php
http://php.net/manual/en/imagick.resizeimage.php
http://php.net/manual/en/imagick.constants.php#imagick.constants.filters
it is very important to optimize your images. Several CMS platforms out there have modules or plugins to preform this process. However if you are programming it yourself there is a complete php tutorial located at this page https://a1websitepro.com/optimize-images-with-php-in-a-directory-on-your-server/ You will be shown how to implement the imagecreatefromjpeg($SrcImage); and imagecreatefrompng($SrcImage); and imagecreatefromgif($SrcImage); There are written and video instruction on the page.

Categories