动态降低图像质量并显示低质量版本


Reduce image quality on the fly and display lower quality version

我有一个使用Wordpress的竞赛网站,允许用户提交图像。共有700多个参赛作品,每个作品最多6张图片,每张图片的最大文件大小为3mb。

然后我列出了所有的条目作为帖子,然后在每个帖子上显示图像。

每张图像用the_field('image1');, the_field('image2');, the_field('image3');等显示。

我遇到的问题是,页面然后试图以3mb的时间加载6个图像。有没有一种方法可以在飞行中优化图像并以50%的质量显示它?

您可以在从数据库(或文件)中提取图片后动态调整图片的大小,而无需创建另一个临时文件。假设你有一个从数据库获取图像的URL。

$pdo = new PDO("somewhere");
$sql = "SELECT image_data FROM pictures WHERE id=1";
$stmt = $pdo->query( $sql );
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$img = imagecreatefromstring($obj->image_data);
header('Content-Type: image/jpeg');
imagejpeg($img, NULL, 50);
imagedestroy($img);

如果您将NULL作为文件名传递给imagejpeg,它将把jpeg写入标准输出。第三个参数是质量级别,在本例中为50%。

上传图片时,可以保存2张图片。1. 原始图像2. 图像的低分辨率副本

因此,当用户查看页面时,在后台下载原始图像时,首先显示低分辨率图像。

你可以很容易地找到一些现成的代码,通过php调整图像的大小。比如这个。http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

$file =  $_GET['file'];//URL with img parameter http://localhost/fk/test.php?file=1.jpeg
$quality = 40; //Change What quality you needed
$location = "images/".$file;
$image = imagecreatefromjpeg($file);
imagejpeg($image, $location, $quality) ;
header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($location));
    header('Content-Disposition: inline; filename="'.$file.'"');
    echo file_get_contents($location);

没有办法动态调整图像的大小。只有一种直接的方法可以让CPU阻塞这种拒绝服务的自我攻击。

图片必须在上传后预先调整到合理的大小和质量。世界上所有的网站都是这么做的