Ray Kelly is speaking out. But why?

Law enforcement guys have a code. Not Kelly.

Law enforcement guys have a code. Often mistreated by their bosses, misunderstood by the media, their ethic is to suck it up and move on.

Not Ray Kelly.

Last week, the most powerful and longest-serving NYC police commissioner lit into Mayor Bill de Blasio — and implicitly NYPD Commissioner Bill Bratton — for limiting Kelly’s controversial stop-and-frisk policy, a move that, he said, has led to an increase in homicides and shootings.

“For over two decades,” he told Fox Business channel last week, “New York City has been made safer as a result of proactive policing, police using their own initiative.” Now, he said he sees “a certain hesitancy on the part of police to engage . . . All signals that are being given lately to police officers: ‘Don’t get involved, don’t engage in this type of practice.’ “

Referring to de Blasio and Bratton’s recent comments dismissing the importance of the crime spike as confined to gang members in only 10 precincts, Kelly said, “For people to say, ‘Oh, they’re only gang members,’ you know, I thought all lives matter. That was a very strange signal from this administration . . .”

Asked from where thoe signals emanated, Kelly said, “From the mayor.”

So why did he speak out?

Was it, as some at Police Plaza say, because his memoir (modestly subtitled “My Life Serving America and Protecting Its Empire City”) is due out in the fall? Was it his 20-year rivalry with Bratton, which began when Bratton replaced him as commissioner in 1994?

Most likely, Kelly wants to protect his legacy, which is being shredded in today’s climate of police distrust. His overuse of stop-and-frisk was declared unconstitutional, resulting in a federal monitor and inspector general — supervision the NYPD had never experienced before.

Even his counterterrorism claims are being questioned. Bratton officials refute Kelly’s assertions that he prevented numerous plots against the city. “Sixteen plots?” a top NYPD official said on condition of anonymity. Alluding to the department’s use of undercovers to track so-called lone-wolf terrorists, the official said, “The NYPD started 13 of them.”

Kelly’s words about increased homicides and shootings resonate, though. Indeed, in the past six months, two cops were assassinated, another was gunned down, a fourth was attacked with a hammer, a fifth with a knife.

In addition, the bad guys are no longer choosing “flight over fight,” as one NYPD top official put it. Instead, they are firing at cops. Recent incidents have occurred in the 101st Precinct in Queens, the 70th in Brooklyn and the 120th in Staten Island.

De Blasio’s denial of increased crime, support of his wife’s former chief of staff despite the anti-cop online postings of her son and boyfriend and his relationship with the Rev. Al Sharpton, have belied any words of support for the NYPD.

Yes, mayor, gestures matter.

Len Levitt