PHP

COMPRESS IMAGES IN PHP

quick guide & example

CREATE IMAGE OBJECT

01

IMAGE OBJECT - USE RESPECTIVE “IMAGE CREATE” FUNCTION $img = imagecreatefrombmp("IMG.BMP"); $img = imagecreatefrompng("IMG.PNG"); $img = imagecreatefromgif("IMG.GIF"); $img = imagecreatefromwebp("IMG.WEBP"); $img = imagecreatefromjpeg("IMG.JPG");

SOURCE IMAGE & MAX DIMENSIONS $sw = imagesx($img); $sh = imagesy($img); $mw = 1920; $mh = 1080; 

RESIZE IMAGE

02

RESIZE USING SMALLER RATIO if ($mw != null && $sw>$mw) { $rw = $mw / $sw; } else { $rw = 1; } if ($mh != null && $sh>$mh) { $rh = $mh / $sh; } else { $rh = 1; } if ($rw!=1 || $rh!=1) {   $rr = $rw<$rh ? $rw : $rh ;   $img = imagescale($img, floor($rr * $sw),    floor($rr * $sh));  }

SAVE - USE RESPECTIVE “IMAGE” FUNCTION. RECOMMENDED - JPG OR WEBP imagejpeg($img, "IMG.JPG", 30); imagewebp($img, "IMG.WEBP", 30); imagepng($img, "IMG.PNG"); imagegif($img, "IMG.GIF");

NOTES * JPG does not support transparent background. * Only WEBP PNG GIF do. * Use WEBP JPEG for best results.

SAVE THE IMAGE

03