PHP

HOW TO CROP IMAGES IN PHP

(quick guide & examples)

ORIGINAL IMAGE $img = imagecreatefrompng(IMG.PNG");

SIMPLE IMAGE CROP

01

CROP 500 X 300 FROM TOP LEFT CORNER $crop = imagecrop($img, [   "x" => 0, "y" => 0,   "width" => 500, "height" => 300 ]);  imagepng($crop, "demo-A.png");

ORIGINAL IMAGE $i = imagecreatefrompng(IMG.PNG"); $swidth = imagesx($img); $sheight = imagesy($img);

CROP FROM CENTER (A)

02

CROP AREA DIMENSIONS (50%) $tocrop = 0.5; $cwidth = ceil($swidth * $tocrop); $cheight = ceil($sheight * $tocrop);

CROP COORDINATES (FROM CENTER) $sx = ceil(($swidth / 2) - ($cwidth / 2)); $sy = ceil(($sheight / 2) - ($cheight / 2)); $area = [   "x" => $sx, "y" => $sy,   "width" => $cwidth, "height" => $cheight ];

CROP FROM CENTER (B)

03

CROP IMAGE $crop = imagecrop($img, $area); imagepng($crop, "demo-B.png");