>  기사  >  백엔드 개발  >  PHP는 GD 라이브러리를 사용하여 고품질 썸네일 이미지 샘플 코드를 생성합니다.

PHP는 GD 라이브러리를 사용하여 고품질 썸네일 이미지 샘플 코드를 생성합니다.

怪我咯
怪我咯원래의
2017-07-12 15:07:221342검색

웹사이트에서 GD 라이브러리는 일반적으로 썸네일을 생성하거나, 사진에 워터마크를 추가하거나, 한자 인증 코드를 생성하거나, 웹사이트 데이터에 대한 보고서를 생성하는 데 사용됩니다. PHP에서 이미지를 처리하려면 GD 라이브러리를 사용할 수 있습니다. 그러나 GIF는 저작권 논란이 있는 LZW 알고리즘을 사용했기 때문에 모든 GIF 지원이 GD 라이브러리 버전 1.6에서 옮겨졌습니다. 이후에는 제외되지만 GD 라이브러리 버전 2.0.28에 다시 추가되었습니다. 둘 중 GD 라이브러리 버전을 사용하는 경우 GIF 관련 기능을 사용할 수 없습니다. 이번 글에서는 주로 GD 라이브러리를 사용하여 PHP에서 고품질 썸네일 이미지를 생성하기 위한 샘플 코드를 소개합니다

다음은 PHP 소스 코드(ResizeImage.php)입니다.

<?php 
$FILENAME="image.thumb"; 
// 生成图片的宽度 
$RESIZEWIDTH=400; 
// 生成图片的高度 
$RESIZEHEIGHT=400; 

function ResizeImage($im,$maxwidth,$maxheight,$name){ 
$width = imagesx($im); 
$height = imagesy($im); 
if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){ 
if($maxwidth && $width > $maxwidth){ 
$widthratio = $maxwidth/$width; 
$RESIZEWIDTH=true; 
} 
if($maxheight && $height > $maxheight){ 
$heightratio = $maxheight/$height; 
$RESIZEHEIGHT=true; 
} 
if($RESIZEWIDTH && $RESIZEHEIGHT){ 
if($widthratio < $heightratio){ 
$ratio = $widthratio; 
}else{ 
$ratio = $heightratio; 
} 
}elseif($RESIZEWIDTH){ 
$ratio = $widthratio; 
}elseif($RESIZEHEIGHT){ 
$ratio = $heightratio; 
} 
$newwidth = $width * $ratio; 
$newheight = $height * $ratio; 
if(function_exists("imagecopyresampled")){ 
$newim = imagecreatetruecolor($newwidth, $newheight); 
imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
}else{ 
$newim = imagecreate($newwidth, $newheight); 
imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
} 
ImageJpeg ($newim,$name . ".jpg"); 
ImageDestroy ($newim); 
}else{ 
ImageJpeg ($im,$name . ".jpg"); 
} 
} 

if($_FILES[&#39;image&#39;][&#39;size&#39;]){ 
if($_FILES[&#39;image&#39;][&#39;type&#39;] == "image/pjpeg"){ 
$im = imagecreatefromjpeg($_FILES[&#39;image&#39;][&#39;tmp_name&#39;]); 
}elseif($_FILES[&#39;image&#39;][&#39;type&#39;] == "image/x-png"){ 
$im = imagecreatefrompng($_FILES[&#39;image&#39;][&#39;tmp_name&#39;]); 
}elseif($_FILES[&#39;image&#39;][&#39;type&#39;] == "image/gif"){ 
$im = imagecreatefromgif($_FILES[&#39;image&#39;][&#39;tmp_name&#39;]); 
} 
if($im){ 
if(file_exists("$FILENAME.jpg")){ 
unlink("$FILENAME.jpg"); 
} 
ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME); 
ImageDestroy ($im); 
} 
} 
?>

다음은 테스트 코드(demo.php)입니다. 코드는 다음과 같습니다.

<?php 
include(&#39;ResizeImage.php&#39;); 
if(!empty($_POST)){ 
echo($FILENAME.".jpg?cache=".rand(0,999999)); 
} 
?> 
<form name="test" action="?submit=true" enctype="multipart/form-data" method="post" > 
<input type="file" name="image" size="50" value="浏览"><p> 
<input type="submit" value="上传图片"> 
</form>


위 내용은 PHP는 GD 라이브러리를 사용하여 고품질 썸네일 이미지 샘플 코드를 생성합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.