Regarding resizing with black bars at top and bottom

how do I resize an image which is rectangle in shape, let us assume 40x60 to a square image, let us assume 30x30, without stretching it, and have black bars at top and bottom instead of stretch?

Have a look here. It’s even doing a bit more than that, but you should be able to find the relevant bits.