Saying that the rapper Daniel Hernandez had “engaged in acts of unsolicited generosity” and “expressed genuine remorse for his actions,” a justice on Friday spared him from prison in connection with sexually explicit videos he made with an underage girl.

Instead the justice, Felicia Mennin of State Supreme Court in Manhattan, sentenced Mr. Hernandez, who performs as Tekashi69 or 6ix9ine, to four years of probation and 1,000 hours of community service.

In 2015, Mr. Hernandez admitted to taking part in making and disseminating the videos, which featured a 13-year-old girl having sex. (A man who had sex with the girl in the videos went to prison.) He received probation as part of a plea agreement, but prosecutors contended he had violated the agreement with two subsequent arrests. They had asked Justice Mennin to send him to prison for one to three years.

Mr. Hernandez, 22, with his long purple, orange and yellow hair and prominent face tattoos, is among the most recognizable of rappers. One of his singles, “Fefe,” recorded with Nicki Minaj, peaked at No. 3 on Billboard Hot 100 chart. Collectively his songs have been viewed hundreds of millions of times on YouTube. He has also become known for feuds with other rappers, including YG and Chief Keef.