【问题标题】:How to crop an image without losing its quality?如何在不损失质量的情况下裁剪图像?
【发布时间】:2018-06-04 17:45:03
【问题描述】:

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

当我尝试通过管理面板裁剪图像时,它可以正常工作。但是当我使用“add_image_size”或“add_filter”功能时,缩略图会失去质量。

这些是我试过的代码。

set_post_thumbnail_size( 212, 159, array( 'center', 'center')  );  

add_image_size( 'qwqeq', 212, 159, array( 'center', 'center' ) );

add_filter('jpeg_quality', function($arg) { return 100; } );  

如何在不使用任何插件的情况下做到这一点?

【问题讨论】:

标签: php wordpress


【解决方案1】:

这是一个使用 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);

【讨论】:

  • 是否可以仅使用 WordPress 功能修复它?因为,正如我在问题中所说,当我使用 wp 管理面板裁剪图像时,上传的图像没有质量。也许我使用的代码有问题。 ?
  • 您的问题是“不使用任何插件”。我不太了解 WP,无法告诉你。但这是您要求的纯 php 解决方案。
  • 我明白了。感谢您的帮助。
猜你喜欢
  • 2014-10-12
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 2021-10-13
  • 1970-01-01
  • 2019-12-13
  • 1970-01-01
相关资源
最近更新 更多