为什么要禁止外链图片?
禁止外链图片是为了保护自己的图片资源,防止其被其他网站盗用,为图片的版权保护提供了基本的保障。
如何禁止外链图片?
要禁止其他网站外链自己的图片,可以通过修改网站的.htaccess文件实现。在文件的末尾添加以下代码:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\\.)?example.com [NC]
RewriteRule \\.(jpg|jpeg|png|gif)$ - [NC,F,L]
其中,把example.com替换成你的网站地址,即可禁止其他网站使用你的图片资源。
如何为网站修改图片?
对于PHP网站,如果需要修改图片,可以使用GD库提供的函数进行处理和生成。比如,你可以通过以下代码来生成一个缩略图:
function thumb($srcFile, $toW, $toH)
{
$arr = getimagesize($srcFile);
$srcW = $arr[0];
$srcH = $arr[1];
$type = $arr[2];
switch ($type) {
case 1: // GIF
$img = imagecreatefromgif($srcFile);
break;
case 2: // JPG
$img = imagecreatefromjpeg($srcFile);
break;
case 3: // PNG
$img = imagecreatefrompng($srcFile);
break;
}
$dstImage = imagecreatetruecolor($toW, $toH);
imagecopyresampled($dstImage, $img, 0, 0, 0, 0, $toW, $toH, $srcW, $srcH);
imagejpeg($dstImage);
}
详见GD库提供的官方文档。