If you happen to use AWSs storage service(S3) for serving your static assets (images to be specific), you can have all your uploads automatically optimized with their serverless product, Lambda. It’s a onetime setup and costs next to nothing from a price standpoint. You upload the original images to one S3 bucket, and the optimized images are automatically stored onto your destination bucket.
In essence, the compression is done by tinyPNG which does the optimizing with lossy compression techniques. The results seem great on both sides i.e. file size (minimum 50% reduction in most cases) and image quality. Their API provides support for most popular programming languages. I have done the setup using Python. In addition to just compressing the images, tinyPNG offers resizing, smart cropping, image cut-out as part of their API. Step-by-step guide in the link below.
PS: tinyPNG offers optimization of the first 500 images for free/month post which charges are applicable (which aren’t much). To know more visit their site.