I don't understand this. Don't you just fit the image to your square, applying the same scale in both x and y directions?
eg if your rectangle was 3 times as wide as it is high, then you would scale it to be 512 pixels wide and (512 / 3) = 171 pixels high, and then vertically center that within the square target ie 171 down from the top of the square.
or to use what I think is your example of a problem:
start with your rectangular 71x29 marker (which I found to be either 70x28 without the black border or 72x30 with the black border, so I went with the one including the black border to make it easier to see what's happening) :
View attachment 162842
and scale that to be 512 pixels wide (ie 512x213) :
View attachment 162843
and then center that within the 512x512 pixel marker size (here using cyan as transparent) :
View attachment 162844
Obviously that image would be a lot sharper if we started from a vector or larger image rather than the 71x29 image from your example.