Likewise, whoever permitted masturbation based on necessity, holds patience is superior to it. For it has been transmitted on authority of Ibn Abbas, may Allah be pleased with him: ‘To marry slave girls is better than masturbation, and it is better than fornication, and since patience is better than marriage to slave girls, then it is also better than masturbation all the more so.’ In particular, a great number of scholars, or a majority of them were also absolutely resolved in prohibiting it, and it is one of the views in the school of Imam Ahmad. Ibn Aqil preferred that view in al-Mufradaat, and the famous view from him – meaning from Imam Ahmad – is that it is prohibited unless one fears hardship. The third view is that it is disliked unless one fears hardship. If Allah said about marriage to slave girls: “And to be patient is better for you.” (al-Nisa 4:25) then there is an element of what is more appropriate in it, and it proves that patience with regards to both [marriage to slave girls and masturbation] is possible. So since He has made permissible what is possible to be patient with, then that is in order to lighten the commandment just as He said: “Allah wishes to lighten for you as man was created weak.” (al-Nisa 4:28)
Masturbation is not permissible according to the majority of scholars past and present regardless of whether one fears hardship. The words of Ibn Abbas, may Allah be pleased with him, and what is transmitted on the authority of Imam Ahmad about it is only for those who fear hardship, which is in this case, fornication and sodomy. One must be in utter fear for himself that he will fall into that, and then in that case it will be permissible for him in order to shatter the strength of his hardship and desire.
As for one who masturbated for enjoyment, or for memory or out of habit, in that he recalls an image while masturbating as if he is being intimate with a woman, then all of that is prohibited and is not the view of Imam Ahmad or anyone else. Some of the scholars have obligated restraint and patience from that as being from among the acts which are obligated and not the recommended acts.
Gardens of Purification by Ibn Taymiyyah Pages 45-46