Linux / Unix Command To Optimize and Compress PNG Files In Bulk
Linux / Unix Command To Optimize and Compress PNG Files In Bulk
You need to use a tool called optipng. It is a PNG optimizer that recompresses image files to a smaller size, without losing any information. This program also converts external formats (BMP, GIF, PNM and TIFF) to optimized PNG, and performs PNG integrity checks and corrections. This tool can be installed on any server powered by Unix or Linux operating systems.
First, turn on EPEL repo and type the following yum command to install optipng:
## ** first enable epel repo on centos 7 ** ##
# yum install epel-release
# yum install optipng
Debian and Ubuntu/Mint Linux user type the following apt-get command to install the same:
$ sudo apt-get install optipng
Why even do this?
Now, normally, optimizing images is part of the build or release process. Before your images even hit your servers, they’re in its most optimal form. However, reality isn’t always that easy. If you run a dynamic site like WordPress or Drupal, anyone can upload images and they don’t necessarily have the same requirements for images like you do.
This technique catches those uploads, encodes them in a better format and nobody notices.
Nobody but you: your server uses less bandwidth and consumes less disk space. This technique also processes asynchronously: there is no delay in the uploads, images are processing a while after they’re uploaded.
Unlike OptiPNG, PNGCrush doesn not overwrite the optimized files, it generates new files. It will be somehow tricky to move all new optimized images one by one, that’s why we can use a single line for loop to make our life easier.
Move to the directory where you are storing your PNG files:
The use this for loop handy script as root:
Exactly the same as when we used OptiPNG, optimizing PNG files with PNGCrush uses find command, then optimizes and saves the new PNG file at /usr/local/src directory, and finally after that it moves the file back to the original location replacing the old file with the new one.
Expected more? That’s all for today. Now you know how to recursively Optimize PNG Files using OptiPNG and PNGCrush tools.
55 responses to “5-Minute PNG Image Optimization”
I think it’s worth mentioning that Smush.it has been integrated into Yslow 🙂
Oh also, on the mac, there’s Ping which is basically an interface for OptiPNG. Here’s the description from the developper:
Unlike similar utilities, Ping is a Universal Binary. Not only that, but we’ve optimized OptiPNG (the underlying tech. that powers Ping) for the latest Intel chips — taking advantage of all the cool (at least to us geeks) features that’re at the heart of Apple’s latest and greatest computers.
I found that Photoshop provides extreme compression for JPG, but not for PNG. Ping comes in handy there.
Excellent article Jeff. I must admit that I normally just “save for web” in Photoshop and haven’t tried OptiPNG or Pngcrush. I’ll give them a try on my next project though 🙂
Thanks! I’ve been using smush.it but didn’t know about the other programs. Do you think it makes a difference whether you smush.it after or before the other optimizations?
In all honesty, through some of my own tests, I have found that PNGOUT provides a better size reduction then both OptiPNG or pngcrush. It also has a nice plugin for Irfanview.
@Jessi: I think that Smush.it is a convenient solution for people who do not want to spend extra time optimizing, but want performance. If you want to have the best results, you should tune each and every image by hand, using Photoshop, and then other tools.
Smush.it is like brute force. It takes all the images and processes them. It works but do not provide the fine tuning you get by hand.
Thanks Louis, nice to know that the pros can do it even better. Since I don’t even do image editing myself and have never owned or used Photoshop, I’ll keep using smush.it, and one of the other programs mentioned here, on the images I’ve been provided.
I don’t know why, but every time I post here, seems like someone is telling me I’m not doing things right! I really appreciate the article.
@Austin: I’d love to see the numbers, and the graphs that confirm you results!
@Jessi: Smash.it does a hell of a job for most people. The two cases where it doesn’t fit are (a) you are perfectionnist and want fine tunning, and (b) you need to have a tool that optimize your images on-the-fly, server-side. You do not want to depend on a tird-party solution there.
@louis: Whatever. I don’t know why you chose to address me when you said the methods in this article weren’t good enough for perfectionists. I never said I was one. Please leave me out of it.
My first comment was mostly intended to communicate my appreciation to the article’s author. (I will find out the answer to my question with my own experimentation.) Jeff, please keep doing what you do. Your articles are terrific!
@Jessi: when I first read your answer to my comment, I missed this line:
I don’t know why, but every time I post here, seems like someone is telling me I’m not doing things right!
I didn’t realize I had offended you. It has never been my intention to be aggressive with you. I like to think that this place is for sharing knowledge, and since you didn’t seem familiar with image optimization, I though I would write a little about the different solutions I know, and what I think about them. I tried to be descriptive/factual but obviously I failed, and you thought I was being contemptuous.
So, again, sorry for that misunderstanding. I was only trying to be helpful here Jessi.
@Louis: apology accepted. I absolutely believe you had good intentions. However, I’d appreciate it so much if in future, you only answer questions I actually ask. If you have criticism or qualifications of the article, great, but they should be addressed to the author, or everyone in general, not me! Thanks Louis, I do wish you the best.
Thanks for this. It has knocked about 10% of most of my PNGs.
Comments are closed for this post. Something to add? Let me know.
How does it work?
When you drag’n’drop images into ImageOptim’s window it will run several image optimization tools automatically and combine their results, ensuring that you always get the smallest file.
A special option for even smaller files
If you enable Lossy minification you’ll get smallest file sizes possible.
By default ImageOptim is very cautious and exactly preserves image quality, but if you allow it to change the quality — even only a little — it will be free to use much more aggressive optimizations that give the biggest results. You can configure lossy optimizations in ImageOptim’s Preferences . ImageOptim can apply lossy compression not only to JPEG , but SVG , anim GIF and PNG as well!
Основное большинство программ и конвертеров создают изображения не очень заботясь об их размере. Поэтому сейчас появляются приложения и сервисы для максимального уменьшения размера самого файла.
Лучший способ сжать изображения оффлайн.
Если вы ищете приложения для компьютера, которое сократит размер ваших файлов без потери качества. При этом еще будет работать в пакетном режиме, то мы советуем обратить внимание на PNGGauntlet.
Вот его преимущества:
- Объединяет PNGOUT, OptiPNG и DeflOpt для создания меньшего размера PNGs
- Без потерь качества изображения — изменяется только размер файла
- Конвертация JPG, GIF, TIFF, и BMP файлов в PNG
- Ультра-комфортный интерфейс
Оптимизация PNG онлайн.
Мы предлагаем использовать наш сервис для оптимизации PNG. Мы, как всегда, ничем не ограничиваем наших пользователей. Вы можете конвертировать файлы любого размера и количества.
Lossy, Glossy or Lossless – which one is the best for me?
Lossy is the best option for most users. The images processed with Lossy algorithms are the smallest optimized images you can get. So, if the speed of your site is paramount and you want the best balance between optimization and picture quality, we recommend you to continue to use Lossy optimization.
Glossy is the best choice if you still care about Google Insights but you believe that a slight loss of page speed is an acceptable compromise for a top notch image quality.
Lossless optimized images are pixel-by-pixel identical with the originals, but they offer a smaller size reduction compared to either Lossy or Glossy processed files. If you want your images to remain untouched, then select this option.
We are using cookies and other similar technologies for the proper operation of our website, for performance analysis, to provide you with personalized content according to your interests and preferences, as well as for anonymous statistics. Our Cookies Policy, available here, provides you with all relevant details regarding the cookies we use and their management.
Please let us know which types of cookies you want to enable on your device, by ticking the relevant boxes below and then press the “OK” button. Necessary cookies cannot be rejected when accessing the website or switched off at a later stage, as they are essential for the proper functionality of the website.
Install our new Android app to optimize the photos on your mobile device and save a lot of space.