php - 背景图像是深色还是浅色?

标签 php gd opendocument

我正在用 PHP 进行 ODP->HTML 转换。我有以下问题:

Use the style:use-window-font-color property to specify whether or not the window foreground color should be as used as the foreground color for a light background color and white for a dark background color.

(OpenDocument 规范版本 1.0、15.4.4)

如果我有一张背景图片,我该如何检查这张图片是浅色还是深色?

你有什么想法吗?

提前致谢, 列乌

最佳答案

我认为这是一个需要解决的非常有趣的问题,所以我编写了一个快速脚本来完成它。遵循提供的其他建议

<?php

    // TODO supply your own filenames
    $filenames = array(
        'testpics/client-bella-vi.jpg',
        'testpics/istockphoto_8577991-concept-of-business-people-crowd.jpg',
        'testpics/medium-gray.jpg');

    // loop though each file
    foreach ($filenames as $filename) {

        echo "$filename<br/>";

        $luminance = get_avg_luminance($filename,10);
        echo "AVG LUMINANCE: $luminance<br />";

        // assume a medium gray is the threshold, #acacac or RGB(172, 172, 172)
        // this equates to a luminance of 170
        if ($luminance > 170) {
            echo "Black Text<br />";
        } else {
            echo 'White Text<br />';
        }

        echo "<br />";
    }
    exit;

    // get average luminance, by sampling $num_samples times in both x,y directions
    function get_avg_luminance($filename, $num_samples=10) {
        $img = imagecreatefromjpeg($filename);

        $width = imagesx($img);
        $height = imagesy($img);

        $x_step = intval($width/$num_samples);
        $y_step = intval($height/$num_samples);

        $total_lum = 0;

        $sample_no = 1;

        for ($x=0; $x<$width; $x+=$x_step) {
            for ($y=0; $y<$height; $y+=$y_step) {

                $rgb = imagecolorat($img, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // choose a simple luminance formula from here
                // http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
                $lum = ($r+$r+$b+$g+$g+$g)/6;

                $total_lum += $lum;

                // debugging code
     //           echo "$sample_no - XY: $x,$y = $r, $g, $b = $lum<br />";
                $sample_no++;
            }
        }

        // work out the average
        $avg_lum  = $total_lum/$sample_no;

        return $avg_lum;
    }

关于php - 背景图像是深色还是浅色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5842440/

相关文章:

php - 拉维尔 4.* : Get all cookies

PHP:使用 ImagePng 创建图像并在单个文件中使用 base64_encode 进行转换?

php - 在 PHP 中合并图像 - GIF 和 JPG

php - 防止 imagejpeg() 保存图像的 EXIF 数据(规范。FileDateTime)

mysql - 如何使用 PHPMyADMIN 在 mysql 中导入两个电子表格?

java - JOpenDocument:空白行和单元格的问题

php - 模块:如何 'unload' native php?

php - 如果元素使用特定的浏览器,有没有办法改变元素的值?

opendocument - "text:s"是什么意思?

php - 如何检查 URL 是否可嵌入 PHP 中的 iframe?