PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to calculate thickness of an object in PNG file using PHP GD library

 October 10, 2022     gd, image-processing, php, php-gd, png     No comments   

Issue

I have a PNG frame and I want to know its thickness. I am able to calculate the width/height of the image itself.

$frame = imagecreatefrompng('frame.png');
// get frame dimentions
$frame_width = imagesx($frame);
$frame_height = imagesy($frame);

But can't figure out a way to calculate thickness of frame, please see image below so see what I mean.

enter image description here

Any suggestions?


Solution

From the last answer it shows that there's no objects in a raster image file. However, you can do it by searching the first occurrence of transparent colour and the first occurrence of the non-transparent colour and calculate the distance of them (assumes that your image's blank area are all transparent).

Example code:

<?php
$img = imagecreatefrompng('./frame.png');//open the image
$w = imagesx($img);//the width
$h = imagesy($img);//the height

$nonTransparentPos = null;//the first non-transparent pixel's position
$transparentPos = null;//the first transparent pixel's position

//loop through each pixel
for($x = 0; $x < $w; $x++){
   for($y = 0; $y < $h; $y++){
        $color = imagecolorsforindex($img,imagecolorat($img,$x,$y));
        if($color['alpha'] < 127 && $nonTransparentPos === null){
            $nonTransparentPos = array($x,$y);
        }
        if($color['alpha'] === 127 && $transparentPos === null){
            $transparentPos = array($x,$y);
        }
   }
   //leave the loop if we have finished finding the two values.
   if($transparentPos !== null && $nonTransparentPos !== null){
        break;
   }
}
$length = $transparentPos[0]-$nonTransparentPos[0];//calculate the two point's x-axis distance
echo $length;
?>


Answered By - Licson
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing