【问题标题】:On-the-fly thumbnails PHP动态缩略图 PHP
【发布时间】:2011-02-25 18:33:36
【问题描述】:

我想出了这个:

<?php 

$dir = $_GET['dir'];

header('Content-type: image/jpeg'); 

$create = imagecreatetruecolor(150, 150); 
$img = imagecreatefromjpeg($dir); 
imagecopyresampled($create, $img, 0, 0, 0, 0, 150, 150, 150, 150); 

imagejpeg($create, null, 100); 

?>

它通过访问来工作:

http://example.com/image.php?dir=thisistheimage.jpg

效果很好......但输出很糟糕:

有人可以将我的代码修复为覆盖黑色区域的 150 x 150 图像吗...

谢谢。

解决方案:

<?php 

$dir = $_GET['dir'];

header('Content-type: image/jpeg'); 

list($width, $height) = getimagesize($dir);

$create = imagecreatetruecolor(150, 150); 
$img = imagecreatefromjpeg($dir); 

$newwidth = 150;
$newheight = 150;

imagecopyresized($create, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagejpeg($create, null, 100); 

?>

【问题讨论】:

  • 您也可以使用 .htaccess 来重写 URL 并具有如下路径:domain.com/imagephp/thisistheimage.jpg
  • 您应该使用文件名中的宽度/高度参数保存调整大小图像的副本,并在处理之前检查它是否存在并提供该副本,以便降低服务器上的负载。还要在 imagejpeg() 之后使用 imagedestroy($create) 来释放内存。

标签: php image-processing image-manipulation on-the-fly


【解决方案1】:

正如其他人所建议的,最后两个参数应该是图像的原始大小。

如果$dir是你的文件名,你可以使用getimagesize获取图片的原始尺寸。

您可以使用 imagecopyresized 或 imagecopyresampled。不同之处在于 imagecopyresized 会复制和调整大小,而 imagecopyresampled 也会重新采样您的图像,这将产生更好的质量。

<?php 

$dir = $_GET['dir'];

header('Content-type: image/jpeg'); 

$create = imagecreatetruecolor(150, 150); 
$img = imagecreatefromjpeg($dir);
list($width, $height) = getimagesize($dir);
imagecopyresampled($create, $img, 0, 0, 0, 0, 150, 150, $width, $height);

imagejpeg($create, null, 100); 

?>

【讨论】:

    【解决方案2】:

    最后 2 个150 应该是全尺寸图片的原始宽度和高度。

    【讨论】:

    • 最好留下评论。这不是答案。
    • 这是对原始未修改问题的完全正确答案。
    • 抱歉,我正在尝试撤消否决票,但它说它已锁定。不过,这是一个懒惰的答案,您应该删除它。
    • 没关系,我不在乎投票否决。是什么使它成为一个懒惰的答案,我自己没有为他编写/更正代码?我认为这根本不会帮助他,是的,它会起作用,但他会知道问题出在哪里吗?我更喜欢向正确的方向轻轻推动。
    【解决方案3】:

    使用imagecopyresized:

    $newwidth = 150;
    $newheight = 150;
    imagecopyresized($create, $image, 0, 0, 0, 0, $newwidth, $newheight, $oldwidth, $oldheight);
    

    【讨论】:

    • $oldwidth 和 $oldheight 的定义是什么?
    • 嗯,当然,现在整理出来,在编辑后的帖子中添加了解决方案:)
    • 本帖无需添加解决方案,建议删除。
    猜你喜欢
    • 2012-08-02
    • 1970-01-01
    • 2019-06-28
    • 2012-12-04
    • 2012-03-29
    • 2015-10-25
    • 2010-10-06
    • 2013-08-24
    相关资源
    最近更新 更多