본문 바로가기

Story/php

php gd image crop 투명 배경 이미지 잘라내기

반응형

이미지 일부분을 잘라내서 보여주는 방법은

Basic way to implement a "crop" feature : given an image (src), an offset (x, y) and a size (w, h).

crop.php :
<?php
$w=$_GET['w'];
$h=isset($_GET['h'])?$_GET['h']:$w;    // h est facultatif, =w par d&#233;faut
$x=isset($_GET['x'])?$_GET['x']:0;    // x est facultatif, 0 par d&#233;faut
$y=isset($_GET['y'])?$_GET['y']:0;    // y est facultatif, 0 par d&#233;faut
$filename=$_GET['src'];
header('Content-type: image/jpg');
header('Content-Disposition: attachment; filename='.$src);
$image = imagecreatefromjpeg($filename);
$crop = imagecreatetruecolor($w,$h);
imagecopy ( $crop, $image, 0, 0, $x, $y, $w, $h );
imagejpeg($crop);
?>

Call it like this :

<img src="crop.php?x=10&y=20&w=30&h=40&src=photo.jpg">

출처 : http://www.sitepoint.com/forums/showthread.php?561308-Php-Image-Crop-Function
위처럼 하면 이미지가 잘려서 보이기는 하지만 투명도가 있는 이미지에선 투명도가 사라지는 문제가 있다.

png 파일의 경우 배경을 투명으로 처리한 경우가 있다. 이 투명배경을 유지한채로 이미지를 잘라내는 방법은 다음과 같다.

$x = $_GET["x"];
$y
= $_GET["y"];
$w
= $_GET["w"];
$h
= $_GET["h"];

// Load the original image.
$img
= imagecreatefrompng($img_path);
imagealphablending
($img, true);

// Create a blank canvas for the cropped image.
$img_cropped
= imagecreatetruecolor($w, $h);
imagesavealpha
($img_cropped, true);
imagealphablending
($img_cropped, false);
$transparent
= imagecolorallocatealpha($img_cropped, 0, 0, 0, 127);
imagefill
($img_cropped, 0, 0, $transparent);

// Crop the image and store the data on the blank canvas.
imagecopyresampled
($img_cropped, $img, 0, 0, $x, $y, $w, $h, $w, $h); // or imagecopy()

// Save the image.
imagepng
($img_cropped, "image_cropped.png", 2);

// Free memory.
imagedestroy
($img);
imagedestroy
($img_cropped);

출처 : http://stackoverflow.com/questions/7368346/how-to-crop-jpg-and-png-with-transparent-background-on-js-jquery

반응형