Reduce image quality in php - 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

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 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.

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.

How can I allow other image formats to be uploaded

This is the code that uploads users logo's I was wondering if anyone could help me.
I want to be able to allow users to upload .png and .gif files too.
Sorry if this is a simple fix but I am very new to php.
<?
//edit logo
function resize_image ($image) {
$imgsize = getimagesize($image);
//check for gallery type to determine thumbnail size
$size_x = 150;
$ratio = 150 / $imgsize[0];
$size_y = $imgsize[1] * $ratio;
$srcimage = ImageCreateFromjpeg ($image);
$newimage = ImageCreateTrueColor($size_x,$size_y);
//$newimage = imagecreate ($size_x, $size_y);
imagecopyresized ($newimage, $srcimage, 0, 0, 0, 0, $size_x, $size_y,
imagesx($srcimage), imagesy($srcimage));
return $newimage;
}
$myrepairer = new repairer;
//resize and upload image
$file = $_FILES['logo']['tmp_name'];
$file_name = $_FILES['logo']['name'];
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.jpg')) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.jpg');
unlink('logos/'.$_REQUEST['id'].'.jpg');
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.jpg');
}
$resultmessage = '<div align="center" class="GreenText">Logo Updated</div>';
You can just get the file extension and use it instead of '.jpg'.
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
So, it'll be something like:
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.'.$ext)) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.'.$ext);
unlink('logos/'.$_REQUEST['id'].'.'.$ext);
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.'.$ext);

Categories