代码之家  ›  专栏  ›  技术社区  ›  Andrea Girardi

如何将图像剪切到网页中

  •  0
  • Andrea Girardi  · 技术社区  · 15 年前

    我想在我的网页上显示图像的一部分。假设原始格式是1024x768,则显示的图像必须是100x768。它不是重新调整大小,而是简单地从0.0像素开始剪切。有什么建议吗?

    6 回复  |  直到 15 年前
        1
  •  8
  •   Sampson    15 年前

    使用CSS的剪辑属性:

    img { position:absolute; clip:rect(0px 60px 200px 0px) }
    

    或者在容器上使用溢出:

    <div style="overflow:hidden; width:100px; height:76px;">
      <img src="myImage.jpg" />
    </div>
    
        2
  •  3
  •   Chris Van Opstal    15 年前

    你可以使用 CSS clip 只显示图像的一部分,如:

    img {
        position:absolute;
        clip:rect(0px,100px,768px,0px);
    }
    
        3
  •  1
  •   usoban    15 年前

    裁剪图像或使用现有的库,宽图像是这种操作的最佳选择之一。

        4
  •  1
  •   Stephen Sorensen    15 年前

    在使用图像编辑器将图像上载到服务器之前,请先裁剪图像。除非出于某种原因你需要整个图像加载但被切断…

        5
  •  1
  •   Alex    15 年前

    另一种解决方案是将图像作为背景图像插入。

    <div style="width: 768px; height: 100px; background: url(theimage.jpg) no-repeat left top;"></div>
    
        6
  •  0
  •   Hugh Bothwell    15 年前

    请注意,CSS解决方案实际上下载了整个图像,然后只显示其顶部。

    根据使用情况,我建议使用动态裁剪脚本或缓存预裁剪图像。

    裁剪脚本应该类似于:

    <?php
    
    // get parameters
    $fname = (string) $_GET['f'];
    $top = (int) $_GET['h'];
    
    // load original
    $old = imagecreatefromjpeg($fname);
    list($width, $height) = getimagesize($fname);
       // N.B. this reloads the whole image! Any way to get
       // width/height directly from $old resource handle??
    
    // create new canvas
    $new = imagecreatetruecolor($width, $top);
    
    // copy portion of image
    imagecopy($dest, $src, 0, 0, 0, 0, $width, $top);
    
    // Output and free from memory
    header('Content-Type: image/jpeg');
    imagejpg($new);
    
    ?>
    

    从您的网页调用,如下所示:

    <img src="crop.php?f=myimg.jpg&h=100" />