If you are okay with always saving as a JPEG and losing any transparency supported by PNG, animations in GIFs, etc, then the above works most of the time.
@TheGarfield very appreciate time it took you to post this reply thanks big time. I am just started to learn PHP and pretty much mu PHP knowledge is limited to creating mybb plugins