Using PHP data structures in C#
Php is full of functions that returns various data structures sometimes quite complicated and not easy to remember. One of most weird structures is return value of getimagesize
. It is an array containing values indexed by both integer and string indices.
Assume output of some example code:
1 |
var_dump(getimagesize("path-to-some-image.jpg")); |
We can expect output like this:
array (size=7)
0 => int 3456
1 => int 2592
2 => int 2
3 => string ’width=”3456″ height=”2592″’ (length=26)
'bits’ => int 8
'channels’ => int 3
'mime’ => string ’image/jpeg’ (length=10)
Following PHP manual we know that index 0 and 1 contains respectively the width and the height of the image. Index 2 is value indicating the type of the image and so on.
Let’s start dreaming about more comfortable way to access image properties. Lang.Php.Graph namespace contains class ImageInfo.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
[AsArray] public class ImageInfo { [ScriptName("0")] public int Width; [ScriptName("1")] public int Height; [ScriptName("2")] public ImageTypes ImageType; [ScriptName("3")] public string HtmlWidthHeight; [ScriptName("bits")] public int Bits; [ScriptName("channels")] public int Channels; [ScriptName("mime")] public string Mime; } |
Note that class is decorated with AsArrayAttribute
so it will not been converted to normal PHP class. Array will be used instead.
Fields are decorated with ScriptNameAttribute
so every C# expression using field of ImageInfo class is converted into PHP array access expression.
For example:
1 2 3 |
var imageInfo = GetImageSize("myImage.jpg"); var width = imageInfo.Width; var mime = imageInfo.Mime; |
Is converted to
1 2 3 |
$imageInfo = getimagesize('myImage.jpg'); $width = $imageInfo[0]; $mime = $imageInfo['mime']; |
What about image type? On PHP side we have integer value. Value 2 (or IMAGETYPE_JPEG constant) indicates Jpeg.
On C# side we have Lang.Php.Graph.ImageTypes
enum. Source:
1 2 |
if (imageInfo.ImageType == ImageTypes.Jpeg) echo("Image type is JPEG"); |
can be translated to:
1 2 |
if ($imageInfo[2] == IMG_JPG) echo 'Image type is JPEG'; |