Popular Categories

How to resize an image by code in WordPress?

I had this issue over a site: Designers Byte for the images loading slowly. This is obviously because of the large image size and file size. To resolve this issue, created a function which resizes the size of an image i.e width and it also reduces the file size. Hopefully this function could be helpful for you as well.

function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height, $type, $attr) = getimagesize($file);

$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
if($type == 2) {
$src = imagecreatefromjpeg($file);
}
if($type == 3) {
$src = imagecreatefrompng($file);
}
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

return $dst;
}

Note: This function is also useful in case of optimization of your site.