All perfect praise be to Allaah, The Lord of the Worlds. I testify that there is none worthy of worship except Allaah, and that Muhammad, sallallaahu ‘alayhi wa sallam, is His slave and Messenger.
We have already clarified in Fatwa 81150 that masturbation is forbidden. If a married person does this, then this act is even more sinful as this is being ungrateful to the bounty of the wife whom Allaah blessed him with and made lawful for him to satisfy his sexual desires with.
Besides, we have already clarified that it is forbidden for a man to imagine an alien woman while having sexual intercourse with his wife, so please refer to Fataawa 84496, 85248 and 87197.
What is even more evil than the above is that that man satisfies his desires while imagining that he prostrates to a woman; as this is a kind of perversion. So, this is not permissible as it is a means of being attached to her [that woman whom he imagines] and doing with her what Allaah has forbidden. However, this act does not reach the level of disbelief just because of this imagination.
On the other hand, the Hadeeth which you referred to in the question was reported by Al-Bukhari and Muslim on the authority of Abu Hurayrah who said: “The Prophet said: “Allaah has pardoned my nation for the (evil) thoughts within themselves as long as they do not speak of it or act upon it.”
However, this Hadeeth does not contradict what we have previously mentioned about the prohibition of such imagination, as this imagination is a means that leads to evil. Indeed, blocking the means to evil is an obligation.
Allaah Knows best.