如何在不损失图像的情况下裁剪图像?

时间:2018-06-04 08:51:23

标签: php wordpress

如何在不损失图像的情况下裁剪图像?

当我尝试通过管理面板裁剪图像时,它没有任何问题。但是当我使用“add_image_size”或“add_filter”函数时,缩略图会丢失它们的质量。

这些是我试过的代码。

* {
    -webkit-print-color-adjust: exact !important;   /* Chrome, Safari */
    color-adjust: exact !important;                 /*Firefox*/
}

如何在不使用任何插件的情况下执行此操作?

1 个答案:

答案 0 :(得分:0)

这是使用php gd库缩放/裁剪图像的功能。你可以修补它,让它做你需要的。

function scaleMyImage($filePath, $newPath, $newSize, $crop = NULL){

  $img = imagecreatefromstring(file_get_contents($filePath));

  $dst_x = 0;
  $dst_y = 0;

  $width   = imagesx($img);
  $height  = imagesy($img);

  $newWidth   = $newSize;
  $newHeight  = $newSize;

  $aspectRatio = $width/$height;

  if($width < $height){  //Portrait.

    if($crop){

      $newWidth   = floor($width * ($newSize / $width));
      $newHeight  = floor($height * ($newSize / $width));
      $dst_y = (floor(($newHeight - $newSize)/2)) * -1;

    }else{

      $newWidth = floor($width * ($newSize / $height));
      $newHeight = $newSize;
      $dst_x = floor(($newSize - $newWidth)/2);

      }


  } elseif($width > $height) {  //Landscape


    if($crop){

      $newWidth   = floor($width * ($newSize / $height));
      $newHeight  = floor($height * ($newSize / $height));
      $dst_x = (floor(($newWidth - $newSize)/2)) * -1;


    }else{

      $newWidth = $newSize;
      $newHeight = floor($height * ($newSize / $width));
      $dst_y = floor(($newSize - $newHeight)/2);

      }


    }

  $finalImage = imagecreatetruecolor($newSize, $newSize);  
  imagecopyresampled($finalImage, $img, $dst_x, $dst_y, 0, 0, $newWidth, $newHeight, $width, $height);

  header('Content-Type: image/jpeg'); //<--Comment out if you want to save to file. Otherwise it will output to your browser.
  imagejpeg($finalImage, $newPath, 60); //3rd param is quality.  60 does good job.  You can play around.

  imagedestroy($img);
  imagedestroy($finalImage);

}  


$filePath = 'path/to/image.jpg'; 
$newPath = NULL; //Set to NULL to output to browser.  Otherwise set a new filepath to save.
$newSize = 400;
$crop = 1;  //Set to NULL if you don't want to crop.

使用:

scaleMyImage($filePath, $newPath, $newSize, 1);