【问题标题】:How can I resize and crop an image with PHP?如何使用 PHP 调整图像大小和裁剪图像?
【发布时间】:2012-05-15 13:47:52
【问题描述】:

我正在寻找某种功能,可以将图像大小调整为 100x100、200x200 等,但保持上传图像的纵横比不变。

我的计划是使用某种裁剪,以便在图像的高度或宽度达到 100 后在图像的中心进行裁剪。

所以我的逻辑有点像这样。

if ( $currentHeight > $currentWidth ) {
  //resize width to 100 and crop top and bottom off so it is 100 high
}

elseif ( $currentWidth > $currentHeight ) {
  //resize height to 100 and crop left and right off so it is 100 wide
}

在我看来,图像将是 100x100,看起来不会很奇怪!

有谁知道我如何在一个整洁的函数中做到这一点??

【问题讨论】:

  • 你搜索了吗? google 或者这个网站,有数百万的例子
  • 你可以先看一下php手册中的图像函数,里面有很多例子
  • Crop image using php的可能重复
  • 我已经搜索了好几天,任何人提供的都是调整宽度或拉伸它。我不想安装一些狡猾的库。我只想要一个简单的功能。能做到吗?

标签: php image resize crop


【解决方案1】:

您还可以使用纯 css 裁剪图像以适应特定尺寸,使用 clip:rect

<style>
/*Size of div that contains the dox*/
.crop{
    float:left;
    position:relative;
    width:100px;
    height:100px;
    margin:0 auto;
    border: 2px solid #474747;
}

.crop img{
    margin:0;
    position:absolute;
    top:-25px;
    left:-25px;
    /*       (Top,Right,Bottom,Left) */
    clip:rect(25px 125px 125px 25px);
}    
</style>

<div class="crop">
    <img src="http://static.php.net/www.php.net/images/php.gif" width="200" title="" alt="" />
<div>
<br/>

<div class="crop">
    <img src="http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=5" title="" alt="" />
<div>

See In Action

【讨论】:

    【解决方案2】:

    这是我的答案 - 我写了一个 imagemagick/php 函数来做到这一点:

    stackoverflow.com/questions/20927238/

    【讨论】:

      【解决方案3】:

      如果你想裁剪中心部分,那么我想计算坐标的逻辑可以是这样的:

      1) 计算作物面积的水平坐标:

      $horizontal_center = $current_width/2;
      $left = $horizontal_center - $new_width/2;
      $right = $horizontal_center + $new_width/2;
      

      2) 计算裁剪区域的垂直坐标:

      $vertical_center = $current_height/2;
      $top = $vertical_center - $new_height/2;
      $bottom = $vertical_center + $new_height/2;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-03
        • 2014-03-24
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2012-12-27
        相关资源
        最近更新 更多