The easiest way to visualize both margins is to plot the openloop transfer function, also called a Nyquist plot.
Now the gain margin is the gain by which you can multiply the transfer function such that it will cross the minus one point. This can be found by finding where the transfer function crosses the negative x-axis. Since applying a gain to the transfer function scales the entire plot uniformly, therefore the gain margin is one over the distance between the negative x-axis crossing and the origin. On a side note: it is possible that the gain margin is infinite if the transfer function does not cross the negative x-axis (excluding the origin itself). This concept can also be translated to a bode plot of the open loop transfer function, but now you have to find the point(s) where the phase is -180° (plus or minus a hole number of times 360°), since that translates to the negative x-axis. The gain margin itself can be found by taking one over the modulus (transforming the dB to normal gain) at those frequencies.
The phase margin is the angle by which the Nyquist plot can be rotated clockwise around the origin before the transfer function would cross the minus one point, or in other words the angle between a point which crosses the unit circle (relative to the origin), the origin and the minus one point. In a bode plot of the transfer function the unit circle translates to the 0 dB line of the magnitude plot, so the phase margin can also be found by looking at the phase at the frequencies of the 0 dB crossings relative to the -180° (plus or minus a hole number of times 360°), since that translates to the phase of the minus one point.
You can actually define a third margin, namely the modulus margin, which is the smallest distance between the transfer function and the minus one point in the Nyquist plot. This also translates to one over the highest value of the sensitivity function.