The case was so bad the Greenock Sheriff sent Gray to the High Court in Edinburgh because he couldn't impose a sentence appropriate to the level of offending.
Judge Nigel Morrison was told that Gray had been interviewed by medical staff and they did not believe he appreciated the level of his offending.
Court appointed social workers also found that Gray was at high risk of reoffending.
Gray pleaded guilty to charges in which he admitted making indecent photographs of children at his home between January 12, 2016 and June 1, 2016.
He also admitted to using a 'public electronic communications network' to send to 'persons unknown' messages of a 'grossly offensive' nature. In these messages, Gray expressed 'a desire' to 'kidnap, sexually abuse, rape and kill babies'.
Gray also pleaded guilty to a charge in which between May 5 2016 and May 6 2016, he sent an offensive message to a person known to prosecutors as 'Back Again.'
He threatened 'Back Again' by claiming he was going to post a series of 'fictitious indecent messages' on the Internet.
The messages - which were faked - were going to show a conversation which Gray said took place between the two of them.
On that occasion, the court heard how Gray organised videos of sadistic sexual assaults on babies into folders on his lap top computer.
He exchanged messages with another person in which they discussed the most extreme sexual violence against babies.
Gray - who began accessing Internet pornography at the age of 13 - sent a message on the Kik messenger app which read: 'I'd kill 25 newborns a night. No mercy.'
He added: 'They're just there for us to abuse.'
Judge Morrison told Gray that he wanted time to consider whether he should impose an extended sentence on him, meaning Gray would be given a fixed prison sentence but would be supervised by the authorities following his release from custody.
But Judge Morrison also said he wanted time to consider whether he should call for a report to see whether Gray should be given an Order for Lifelong Restriction.
This order would mean that Gray could spend the rest of his life in prison. He would only be released from custody if the parole board considered he no longer posed a threat to public safety.
On Monday, Judge Morrison ruled that he decided it was appropriate for him to impose an extended sentence.
After serving five years, Gray will be supervised by the authorities for three years following his release from prison.
Police who seized Gray's computer found he had 19,884 images made up of 16,120 still pictures and 3,764 videos.
These included 1,864 pictures and 2,254 moving images of category A abuse, the worst level.
The age range of the children who were abused was less than a year to 12-years-old.