Crop Image From Center PHP

后端 未结 4 1045
梦如初夏
梦如初夏 2020-12-05 05:40

I want to crop an image from the center in the size 200 * 130 the image to be cropped may vary in size, if the image is smaller we wont crop it i know how to this part where

4条回答
  •  庸人自扰
    2020-12-05 06:37

    GD comes bundled with all PHP installations from version 4.3.6 onwards so chances are, you have it.

    Here's the steps you need to take...

    1. Create an image resource using one of the GD imagecreatefrom*() functions. The one you use depends on the type of image you're dealing with
    2. Determine the image dimensions using imagesx() and imagesy()
    3. Determine your crop coordinates using the following algorithm and crop using imagecopy()

    Find crop coordinates

    $width  = imagesx($img);
    $height = imagesy($img);
    $centreX = round($width / 2);
    $centreY = round($height / 2);
    
    $cropWidth  = 200;
    $cropHeight = 130;
    $cropWidthHalf  = round($cropWidth / 2); // could hard-code this but I'm keeping it flexible
    $cropHeightHalf = round($cropHeight / 2);
    
    $x1 = max(0, $centreX - $cropWidthHalf);
    $y1 = max(0, $centreY - $cropHeightHalf);
    
    $x2 = min($width, $centreX + $cropWidthHalf);
    $y2 = min($height, $centreY + $cropHeightHalf);
    

    Feel free to use my image manipulation class, it should make some aspects much easier - https://gist.github.com/880506

    $im = new ImageManipulator('/path/to/image');
    $centreX = round($im->getWidth() / 2);
    $centreY = round($im->getHeight() / 2);
    
    $x1 = $centreX - 100;
    $y1 = $centreY - 65;
    
    $x2 = $centreX + 100;
    $y2 = $centreY + 65;
    
    $im->crop($x1, $y1, $x2, $y2); // takes care of out of boundary conditions automatically
    $im->save('/path/to/cropped/image');
    

提交回复
热议问题