【问题标题】:Scale images down to an app optimized size using PHP使用 PHP 将图像缩小到应用优化的大小
【发布时间】:2016-01-08 20:08:59
【问题描述】:

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

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

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

【问题讨论】:

    标签: php cakephp image-processing cakephp-2.7


    【解决方案1】:

    您可能想尝试Adaptive Images 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;
      

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

    【讨论】:

    • 这听起来很有趣,但可能无法正常工作,因为我通过 JSON API 获取数据。
    • 恐怕不会。这仅适用于作为文件存储在文件系统中的图像。
    【解决方案2】:

    使用 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
    

    【讨论】:

    • 谢谢,但不幸的是它没有回答这个问题。我不知道新的高度和宽度。
    • 新的高度和宽度将取决于文件格式、原始高度和宽度、文件大小以及可以压缩的程度。没有一个简单的答案。您将不得不进行一些研究和实验,以确定您需要重新缩放图像多少才能满足特定的文件大小目标。
    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 2020-06-14
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 2015-05-31
    相关资源
    最近更新 更多