Way to verify if variable is a valid GD image resource?
Asked Answered
B

4

10

I have a class that accepts a GD image resource as one of its arguments. As far as I know, there is no way to type hint this since it is a resource and not an object. Is there a way to validate whether the supplied argument is a valid GD image resource (aside from further functionality using this resource failing)?

PS: Please do not mention ImageMagick in your answer...

Banderilla answered 10/5, 2011 at 22:2 Comment(0)
D
10

The get_resource_type function should help you out. Short of writing code and seeing what it return, I'm not sure what it's going to say for a GD resource, so you're on your own there. Should be a good starting point, though!

Discomfit answered 10/5, 2011 at 22:12 Comment(0)
M
15

Starting with PHP 8.0, get_resource_type with a GD image argument, will throw a Fatal Error:

PHP Fatal error: Uncaught TypeError: get_resource_type(): Argument #1 ($resource) must be of type resource, GdImage given.

We should use get_class() function. PHP documentation states:

Explicitly passing null as the object is no longer allowed as of PHP 7.2.0. The parameter is still optional and calling get_class() without a parameter from inside a class will work, but passing null now emits an E_WARNING notice.

So, the correct way to check this, in PHP 8.0 should be:

function is_gd_image($var) : bool {
    return (gettype($var) == "object" && get_class($var) == "GdImage");
}
Menefee answered 16/1, 2021 at 7:21 Comment(0)
D
10

The get_resource_type function should help you out. Short of writing code and seeing what it return, I'm not sure what it's going to say for a GD resource, so you're on your own there. Should be a good starting point, though!

Discomfit answered 10/5, 2011 at 22:12 Comment(0)
V
9

get_resource_type() returns "gd" if the resource is a gd image, so that's what you need.

Vevina answered 10/5, 2011 at 22:22 Comment(1)
Thanks! Steve was first however.Banderilla
G
0
if (is_resource($image) || $image instanceof \GdImage)
{

}

do a check

Greet answered 23/3, 2023 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.