本文主要是介绍分享一段程序代码:用PHP做图片锐化程序[绝对好用],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
做相册缩略图程序,上传后图片要自动生成缩略图,并且要锐化一下。上网搜索了一下,结果效果一点也不好,找来找去,天下怎么都是一样的代码?
没办法,只好去老外那里淘一淘了,结果发现这个非常不错,现在分享给大家了,呵呵。
<?php
function GDThrowError($message)
{
// don't throw plain text errors in a function that's supposed to return an image
// as per "the principle of least astonishment": the user is expecting
// a jpeg, and they'll be less astonished to get a JPEG error message
// than they would be if they got plain text. Imagine this was called
// from an image tag, which makes sense, that's how you use images:
// plain text errors won't even reach most users, they'd have to copy
// the img src into the address bar. It probably wont' even occur to
// them, as it's not typically helpful to view the source of an image
// resource.
$font = 2;
// create a canvas with a bit of padding
$errimg = imagecreate((imagefontwidth($font) * strlen($message)) + 20, imagefontheight($font) + 10);
$bg = imagecolorallocate($errimg, 255, 255, 255);
$textcol = imagecolorallocate($errimg, 0, 0, 0);
imagestring($errimg, 2, 10, 5, $message, $textcol);
header('Content-type: image/jpeg');
imagejpeg($errimg);
imagedestroy($errimg);
}
function GDMakeJpegLookLikeCrap($target)
{
// image dimensions are no longer needed (see below), but getimagesize can do some simple validation
if (($dims = @getimagesize($target)) === false || $dims['mime'] != 'image/jpeg')
{
GDThrowError('The file you specified couldn\'t be found or is not a valid jpeg image. Make sure you spelled it correctly and provided the correct path.');
return(false);
}
// the original function creates a new image and resamples the source to it using the same height and width here.
// I imagine this was to add future resizing functionality but as it is it does nothing but waste resources
$image = imagecreatefromjpeg($target);
// don't really know/care what this is. If you're interested see http://us2.php.net/imageconvolution
// try tweaking these three vars for different effects, but there is a sharpening function in the php docs (above links) and it's not a trivial operation
$spnMatrix = array( array(-1,-1,-1,),
array(-1,16,-1,),
array(-1,-1,-1));
$divisor = 8;
$offset = 0;
imageconvolution($image, $spnMatrix, $divisor, $offset);
// I like to send headers as late as possible to avoid already sent errors and duplicate header content
header('Content-type: image/jpeg');
imagejpeg($image, null, 100);
imagedestroy($image);
}
// example call
$s_image = (isset($_GET['image'])) ? $_GET['image'] : null;
if (preg_match('/\.(jpg|jpeg)$/i', $s_image))
{
GDMakeJpegLookLikeCrap($s_image);
}
else
{
GDThrowError('Please specify a jpeg file to sharpen in the form: ' . $_SERVER['PHP_SELF'] . '?image=filename.jpg');
}
?>
这篇关于分享一段程序代码:用PHP做图片锐化程序[绝对好用]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!