Heim  >  Artikel  >  Backend-Entwicklung  >  php header函数输出图片缓存实现代码

php header函数输出图片缓存实现代码

WBOY
WBOYOriginal
2016-07-25 08:52:17992Durchsuche
  1. // put this above any php image generation code:
  2. session_start();
  3. header("Cache-Control: private, max-age=10800, pre-check=10800");
  4. header("Pragma: private");
  5. header("Expires: " . date(DATE_RFC822,strtotime(" 2 day")));
复制代码

在header("Content-type: image/jpeg");添加这段代码,它将规定当前页面缓存的时间(两天),并在下一次访问中使用这个缓存时间节点。 接下来判断是否已经有缓存,如果有,就使用缓存。

情况一:如果浏览器对当前页面已经有缓存,那么就直接使用它。

  1. // the browser will send a $_SERVER['HTTP_IF_MODIFIED_SINCE'] if it has a cached copy
  2. if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
  3. // if the browser has a cached version of this image, send 304
  4. header('Last-Modified: '.$_SERVER['HTTP_IF_MODIFIED_SINCE'],true,304);
  5. exit;
  6. }
复制代码

情况二:浏览器缓存了当前页,虽然更新了某些图片信息,但来源图片本身没有变化,而且希望使用之前的缓存,那么也使用缓存。

  1. $img = "some_image.png";
  2. if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == filemtime($img))) {
  3. // send the last mod time of the file back
  4. header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($img)).' GMT',true, 304);
  5. exit;
  6. }
复制代码

当然,有些特殊的情况我们还必须考虑,记得把它们都放在header("Content-type: image/jpeg")的上面。

例子:

  1. //调整图片大小
  2. /**
  3. *图片按比例调整大小的原理:
  4. *1、比较原图大小是否小于等于目标大小,如果是则直接采用原图宽高
  5. *2、如果原图大小超过目标大小,则对比原图宽高大小
  6. *3、如:宽>高,则宽=目标宽, 高=目标宽的比例 * 原高
  7. *4、如:高>宽,则高=目标高,宽=目标高的比例 * 原宽
  8. **/ bbs.it-home.org
  9. $image = "test.jpg";
  10. $max_width = 200;
  11. $max_height = 200;
  12. $size = getimagesize($image); //得到图像的大小
  13. $width = $size[0];
  14. $height = $size[1];
  15. $x_ratio = $max_width / $width;
  16. $y_ratio = $max_height / $height;
  17. if (($width {
  18. $tn_width = $width;
  19. $tn_height = $height;
  20. }
  21. elseif (($x_ratio * $height) {
  22. $tn_height = ceil($x_ratio * $height);
  23. $tn_width = $max_width;
  24. }
  25. else
  26. {
  27. $tn_width = ceil($y_ratio * $width);
  28. $tn_height = $max_height;
  29. }
  30. $src = imagecreatefromjpeg($image);
  31. $dst = imagecreatetruecolor($tn_width, $tn_height); //新建一个真彩色图像
  32. imagecopyresampled($dst, $src, 0, 0, 0, 0,$tn_width, $tn_height, $width, $height); //重采样拷贝部分图像并调整大小
  33. header('Content-Type: image/jpeg');
  34. imagejpeg($dst,null,100);
  35. imagedestroy($src);
  36. imagedestroy($dst);
  37. ?>
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn