Example of PHP method for compressing picture size and converting it to jpg format

  • 2021-09-24 21:55:02
  • OfStack

In this paper, an example is given to describe the method of compressing picture size by PHP and converting it into jpg format. Share it for your reference, as follows:


<?php
function ImageToJPG($srcFile,$dstFile,$towidth,$toheight)
{
  $quality=80;
  $data = @GetImageSize($srcFile);
  switch ($data['2'])
  {
  case 1:
    $im = imagecreatefromgif($srcFile);
    break;
  case 2:
    $im = imagecreatefromjpeg($srcFile);
    break;
  case 3:
    $im = imagecreatefrompng($srcFile);
    break;
  case 6:
  $im = ImageCreateFromBMP( $srcFile );
  break;
  }
  // $dstX=$srcW=@ImageSX($im);
  // $dstY=$srcH=@ImageSY($im);
  $srcW=@ImageSX($im);
  $srcH=@ImageSY($im);
  //$towidth,$toheight
  if($toheight/$srcW > $towidth/$srcH){
    $b = $toheight/$srcH;
  }else{
    $b = $towidth/$srcW;
  }
  // Calculate the width and height of the scaled picture 
  // floor  Discard the decimal point and round it 
  $new_w = floor($srcW*$b);
  $new_h = floor($srcH*$b);
  $dstX=$new_w;
  $dstY=$new_h;
  $ni=@imageCreateTrueColor($dstX,$dstY);
  @ImageCopyResampled($ni,$im,0,0,0,0,$dstX,$dstY,$srcW,$srcH);
  @ImageJpeg($ni,$dstFile,$quality);
  @imagedestroy($im);
  @imagedestroy($ni);
}
//ImageToJPG(' Source file name ',' Destination file name ', Target width , High target );
ImageToJPG('test2.png','test2.jpg',80,50);

More readers interested in PHP can check the topic of this site: "PHP Graphics and Picture Operation Skills Summary", "php File Operation Summary", "PHP Array (Array) Operation Skills Encyclopedia", "PHP Basic Grammar Introduction Course", "PHP Operation and Operator Usage Summary", "php Object-Oriented Programming Introduction Course", "PHP Network Programming Skills Summary", "php String (string) Usage Summary", "php+mysql Database Operation Introduction Course" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: