A police officer shot and critically wounded a man who ambushed him in a Harlem park on Thursday, officials said.

The nine-year-veteran was alone on foot patrol in a remote section of Marcus Garvey Park around 1:35 p.m. Thursday, when the suspect, Daniel Cabrera, 28, of White Plains, repeatedly punched him, police said.

The officer tried several times to subdue the assailant and even used pepper spray, but he would not stop the assault, police said.

The cop finally pulled out his service weapon and fired a single shot into the 28-year-old man’s torso, police said.

The officer, who is in his 30s and assigned to the 25th Precinct, was taken to St. Luke’s Hospital for injuries to his face.

At least two witnesses backed up the NYPD’s account of the incident.

“There was a cop up there and there was someone else doing something he wasn’t supposed to do — drugs I think — the cop told him to stop and he wouldn’t stop, and they had a bit of a fight,” one woman who heard the fight and the single gunshot told The Post.

“The cop got punched in the mouth, and I guess he defended himself.”

Cabrera was treated for the gunshot wound at Harlem Hospital, and hit with multiple charges, including assaulting and menacing a cop, officials said.