Home > Backend Development > PHP Tutorial > Example of PHP method to compress image size and convert to jpg format_php tips

Example of PHP method to compress image size and convert to jpg format_php tips

jacklove
Release: 2023-04-01 19:20:02
Original
1950 people have browsed it

This article mainly introduces the method of PHP to compress the image size and convert it to jpg format, involving PHP's related operating skills for image reading, calculation, conversion, output, etc. Friends who need it can refer to it

The example of this article describes the method of compressing image size and converting it to jpg format in PHP. Share it with everyone for your reference, the details are as follows:

<?php
function ImageToJPG($srcFile,$dstFile,$towidth,$toheight)
{
  $quality=80;
  $data = @GetImageSize($srcFile);
  switch ($data[&#39;2&#39;])
  {
  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;
  }
  //计算出图片缩放后的宽高
  // floor 舍去小数点部分,取整
  $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(&#39;源文件名&#39;,&#39;目标文件名&#39;,目标宽,目标高);
ImageToJPG(&#39;test2.png&#39;,&#39;test2.jpg&#39;,80,50);
Copy after login

## Articles you may be interested in:

PHP Method Example of Remembering Status When Searching_php Tips

The laravel project uses twemproxy to deploy the complete steps of redis cluster php instance

How to enable Opcode in PHP7 to create powerful performance Detailed explanation of php skills








The above is the detailed content of Example of PHP method to compress image size and convert to jpg format_php tips. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template