Crop dan Resize Gambar dari URL


Script ini saya gunakan untuk menampilkan thumbnail berita, kenapa saya “resize” dan “crop”? alasannya supaya ukurannya pas dan tidak memberatkan saat membuka website.

Lansung saja scriptnya :

<?php 

        $url="http://localhost/namagambar.jpg";
	$image = imagecreatefromjpeg($url);
	$filename = 'cropped_whatever.jpg';

	$thumb_width = 150;
	$thumb_height = 150;

	$width = imagesx($image);
	$height = imagesy($image);

	$original_aspect = $width / $height;
	$thumb_aspect = $thumb_width / $thumb_height;

	if ( $original_aspect >= $thumb_aspect )
	{
	   // If image is wider than thumbnail (in aspect ratio sense)
	   $new_height = $thumb_height;
	   $new_width = $width / ($height / $thumb_height);
	}
	else
	{
	   // If the thumbnail is wider than the image
	   $new_width = $thumb_width;
	   $new_height = $height / ($width / $thumb_width);
	}

	$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

	// Resize and crop
	imagecopyresampled($thumb,
	                   $image,
	                   0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
	                   0 - ($new_height - $thumb_height) / 2, // Center the image vertically
	                   0, 0,
	                   $new_width, $new_height,
	                   $width, $height);
	

	header('Content-Type: image/jpeg');
	imagejpeg($thumb);

?>

untuk demonya silahkan di coba di sini

sumber

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s