0

我正在开发一个应用程序,用户可以将图像上传到存储它们的位置(到我的 CakePHP 2.7.2 后端服务器)。这些图像有时会很大(例如大约 7-8 MB 的 iPhone 图像)。

该应用程序在应用程序中显示这些图像(但由于必须下载大数据,这需要很长时间)。

使用 PHP 将图像缩小到 30kB 大小的最佳方法是什么?我希望图像在尺寸和质量上都有效。重要的要求是必须保持宽度和高度的比例!

4

2 回答 2

1

您可能想尝试自适应图像PHP 脚本。

自适应图像检测您的访问者的屏幕尺寸,并自动创建、缓存和提供您网页嵌入的 HTML 图像的适合设备的重新缩放版本。无需标记更改。它旨在与响应式设计一起使用,并与流体图像技术结合使用。

让它在 CakePHP 中工作:

  1. 下载到你的/app/webroot/文件夹

  2. 修改您/app/webroot/.htaccess并在 CakePHP mod_rewrite 规则之前添加以下内容:

    RewriteCond %{REQUEST_URI} !optional_path_to_exclude/
    RewriteRule \.(?:jpe?g|gif|png)$ adaptive-images.php [L]
    
  3. 编辑/app/webroot/adaptive_images.php并替换第 16 行:

    $cache_path    = "ai-cache"; 
    

    $cache_path    = "/app/tmp/cache/ai-cache/"; 
    

    第 30 行:

    $source_file    = $document_root.$requested_uri;
    

    $source_file    = $document_root.'/app/webroot'.$requested_uri;
    

最后一步可能会因您的虚拟主机配置而异。

于 2016-01-08T21:22:13.587 回答
0

使用 PHP 处理图像有两种主要方法:GDImageMagick

对于 GD,重新缩放图像最容易使用imagecopyresampled()完成。您将需要大致遵循以下几行的代码:

$image = imagecreatefromstring($imageContents); //or one of the image imagecreatefrom* functions
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);

ob_start();
imagepng($newImage, null); //or imagejpeg as appropriate
$output = ob_get_contents();
ob_end_clean();

//do something with $output
于 2016-01-08T20:21:15.173 回答