Compress images with imagemagick for php

1

Hello community good afternoon someone around here has used the imagemagick library with php to compress images since I am using a function but I do not veil the changes when I check the weight of the images, that code is what is in an example of the documentation.

namespace Compacted_Imagick;

class Compacted_Imagick {

/*
 * Configuracion inicial
 */

public  $setting = [
    'degrees' => 360,
    'length' => 16,
    'startlength' => 97,
    'lastlength' => 122,
    'patronspaces' => '/\W/'
];


public function compresed($file,$output,$quality) {
    $img = new \Imagick($file);
    $imgmagick = new \Imagick();

    $imgmagick->setcompressionquality($quality);
    $imgmagick->newpseudoimage(
            $img->getimagewidth(),
            $img->getimageheight(), 'canvas:white');
    $imgmagick->setformat('jpg');

    return $output = $img->getimageblob();
  }
}

Here is an example of how I use this function

public function processImage() {
    require_once (ROOT.DS.'vendor'.DS.'imagickcompacted'.DS.'Compacted_Imagick.php');
    if($this->request->is('post')){
        $imgtmp = $this->request->data['name_imagen'];
        if($imgtmp['name'] != NULL){
           //esta es mi clase que contiene la funcion
            $img = new \Compacted_Imagick\Compacted_Imagick();
            $dir = new Folder();
            $dir->create(ROOT.DS.'tmpupload'.DS.$this->Auth->user('person_id'),TRUE, 0755);
            $mv = new File($imgtmp['tmp_name']);
            $mv->copy(ROOT.DS.'tmpupload'.DS.$this->Auth->user('person_id').DS.$imgtmp['name']);
            $path = ROOT.DS.'tmpupload'.DS.$this->Auth->user('person_id').DS.$imgtmp['name'];
            //Aqui obtengo la extensión para crear el nuevo archivo 
            $ext = pathinfo($imgtmp['name'],PATHINFO_EXTENSION);
           //aqui el nuevo nombre de la imagen
            $name_image_2 = $img->uniquename();
            //luego la ruta donde se copiara la imagen
            $path_copy = ROOT.DS.'tmpupload'.DS.$this->Auth->user('person_id').DS.$name_image_2.'.'.$ext;
            //por ultimo mi función que procesa la imagen
            $img->compresed($path, $path_copy, 25);
            echo json_encode($imgtmp['name']);
            die();
        }
    }
    $this->autoRender = false;
}

The problem is that I do not see that the file is created try to write the same image but check the weight in megabytes and weighs the same as when the image was uploaded

    
asked by Jonathan Cunza 12.02.2018 в 22:25
source

2 answers

1

Hello Community, here I put my solution with the imagemagick library

  //Funcion que comprime y corta la imagen sin perder su calidad
  public function compresed($path,$file,$ext,$quality) {

    $this->rotate($file);
    $img = new \Imagick($file);
    $img->setcompressionquality($quality);
    $img->resizeimage(400, 600,  \Imagick::FILTER_LANCZOS,1,TRUE);
    $img->setFormat("jpg");
    $img_name = $this->uniquename();
    $img->writeimages($path.DS.$img_name.'.'.$ext,true);
    return $img_name.'.'.$ext;
}
 //Función para rotar la imagen en caso sea subida desde un celular
public function rotate($file) {

    $exif = exif_read_data($file);
    $img = new \Imagick($file);
    if(isset($exif['Orientation']) && $exif['Orientation'] == '6'){
        $img->rotateimage('black', $this->setting['degrees']);
    }
    if(isset($exif['Orientation']) && $exif['Orientation'] == '3'){
        $img->rotateimage('black', $this->setting['degrees']);
    }

    return $file;
}

I hope it will help someone who needs it thanks to the rest for their answers:)

    
answered by 15.02.2018 / 18:48
source
1

Hello friend, I recommend you use imagecreatefromstring ()

Here I leave an example of its use if you're looking to take the weight off the images.

This function takes an image file name, then loads,

converts it and saves it as a new file. The arguments.

Those required are:

$ fromfile: Path and / or name of the image to be converted

$ tofile: path and / or name of the image to be converted

$ type: File type to convert:

"gif": Convert to a gif image

"jpeg": convert to a jpeg image

"png": Convert to a png image

$ quality: Image quality (0-99).

Only used if the $ type is jpeg or png

0 = lowest quality and smallest size

99 = The best quality and the largest size

PIPHP_ImageConvert("photo.jpg", "photo4.png", "png", 0);

function PIPHP_ImageConvert($fromfile, $tofile, $type, $quality)
{
   $contents = file_get_contents($fromfile);
   $image    = imagecreatefromstring($contents);

   switch($type)
   {
      case "gif":  imagegif($image,  $tofile); break;
      case "jpeg": imagejpeg($image, $tofile, $quality); break;
      case "png":  imagepng($image,  $tofile,
                     round(9 - $quality * .09)); break;
   }
}





<?

$origen="img/imagen.jpg";

$destino="img/nuevaimagen.jpg";

$destino_temporal=tempnam("tmp/","tmp");

redimensionar_jpeg($origen, $destino_temporal, 300, 350, 100);



// guardamos la imagen

$fp=fopen($destino,"w");

fputs($fp,fread(fopen($destino_temporal,"r"),filesize($destino_temporal)));

fclose($fp);



// mostramos la imagen

echo "<img src='img/nuevaimagen.jpg'>";



function redimensionar_jpeg($img_original, $img_nueva, $img_nueva_anchura, $img_nueva_altura, $img_nueva_calidad)

{

    // crear una imagen desde el original 

    $img = ImageCreateFromJPEG($img_original);

    // crear una imagen nueva 

    $thumb = imagecreatetruecolor($img_nueva_anchura,$img_nueva_altura);

    // redimensiona la imagen original copiandola en la imagen 

    ImageCopyResized($thumb,$img,0,0,0,0,$img_nueva_anchura,$img_nueva_altura,ImageSX($img),ImageSY($img));

    // guardar la nueva imagen redimensionada donde indicia $img_nueva 

    ImageJPEG($thumb,$img_nueva,$img_nueva_calidad);

    ImageDestroy($img);

}

?>
    
answered by 13.02.2018 в 01:07