使用PHP检查图像URL是否透明

时间:2017-02-21 16:04:43

标签: php

我想查看像https://something.com/my/render_thumb.php?size=small这样的iamge网址,看它是否透明,因为如果它部分透明,那么我会认为它是完全透明的,然后在我的代码中使用不同的图像。我试图创建一个像这样读取URL的函数,但它抱怨$ url是string类型的东西。关于如何快速查看图片网址的任何想法?

// --pseudo php code (doesn't work) --
function check_transparent($url) {

    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $raw = curl_exec($ch);
    curl_close ($ch);

    $img = ImageCreateFromJpeg($raw);
    // We run the image pixel by pixel and as soon as we find a transparent pixel we stop and return true.
    for($i = 0; $i < 10; $i++) {
        for($j = 0; $j < 10; $j++) {
            $rgba = imagecolorat($img, $i, $j);
            if(($rgba & 0x7F000000) >> 24) {
                return true;
            }
        }
    }

    // If we dont find any pixel the function will return false.
    return false;
}

2 个答案:

答案 0 :(得分:2)

您的问题与您使用ImageCreateFromJpeg功能的方式有关。

Check out PHP docs你会发现函数需要一个有效的JPEG路径或URL,而不是它的原始值。所以这应该是你函数的第一行:

$img = ImageCreateFromJpeg($url);

答案 1 :(得分:0)

谢谢,所以可能这样的事情可以解决这个问题....会给它一个机会......

function getImageType($image_path) {
$typeString = '';
$typeInt = exif_imagetype($image_path);
switch ($typeInt) {
    case IMAGETYPE_GIF:
    case IMG_GIF:
        $typeString = 'image/gif';
        break;
    case IMG_JPG:
    case IMAGETYPE_JPEG:
    case IMG_JPEG:
        $typeString = 'image/jpg';
        break;
    case IMAGETYPE_PNG:
    case IMG_PNG:
        $typeString = 'image/png';
        break;
    default:
        $typeString = 'other ('.$typeInt.')';
}
return $typeString;
}


function check_transparent($url) {

$imgType = '';
$imgType = getImageType($url);

if ($imgType == 'image/jpg') {
    $img = ImageCreateFromJpeg($url);
} else if ($imgType == 'image/png') {
    $img = ImageCreateFromPng($url);
} else {
    return false;
}

// We run the image pixel by pixel and as soon as we find a transparent pixel we stop and return true.
for($i = 0; $i < 200; $i++) {
    for($j = 0; $j < 200; $j++) {
        $rgba = imagecolorat($img, $i, $j);
        if(($rgba & 0x7F000000) >> 24) {
            return true;
        }
    }
}

// If we dont find any pixel the function will return false.
return false;
}

示例:

$url = "https://example.com/images/thumb_maker.php?size=200x200";

echo check_transparent($url);