Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Como alterar a compactação de imagens JPEG do WordPress

O WordPress pode usar a compactação para tornar as imagens do seu site menores. Isso torna o download mais rápido, melhorando o tempo de carregamento do seu site.

Mas se suas imagens forem muito comprimidas, elas podem parecer menos nítidas ou de qualidade inferior. Isso não dará a melhor impressão aos visitantes do site.

Recentemente, um de nossos leitores perguntou se era possível alterar as configurações de compactação de imagens JPEG no WordPress. A resposta é sim.

Neste artigo, mostraremos como aumentar ou diminuir a compactação de imagens JPEG no WordPress, para que você possa encontrar o equilíbrio perfeito entre a qualidade da imagem e a velocidade do site.

Por que alterar a compactação de imagem JPEG do WordPress?

Toda vez que você carrega uma imagem JPEG em seu site WordPress, ele comprime automaticamente a imagem com 90% de qualidade. Já no WordPress 4.5, esse número foi reduzido para 82% para melhorar o desempenho do site para usuários móveis.

Se você for um fotógrafo que deseja exibir imagens de alta qualidade em seu site, poderá desativar a compactação de imagens no WordPress.

Como desativar a compactação de imagens no WordPress

Tudo o que você precisa fazer é colar o seguinte código no arquivo functions.php do seu tema manualmente ou usando um plug-in de snippet de código como o WPCode (recomendado).

Se você nunca fez isso antes, consulte nosso guia sobre como adicionar código personalizado ao seu site WordPress.

Primeiro, você precisa instalar o plugin WPCode Free Plugin. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.

Após a ativação, você precisa navegar até Code Snippets ” + Add Snippet no painel do WordPress. Depois disso, passe o mouse sobre o modelo “Add Custom Code” (Adicionar código personalizado) e clique no botão “Use Snippet” (Usar snippet).

Adding a New Snippet in WPCode

Isso o levará a uma nova tela na qual poderá criar seu snippet personalizado. Você precisa adicionar um título ao snippet, como “Desativar compressão de imagem no WordPress”.

Depois disso, você deve selecionar “PHP Snippet” no menu suspenso Code Type (Tipo de código) e, em seguida, colar o seguinte trecho de código no painel “Code Preview” (Visualização de código).

add_filter('jpeg_quality', function($arg){return 100;});
Disabling Image Compression Using WPCode

Quando você define o valor como 100, o WordPress comprime a imagem em sua qualidade máxima.

Por fim, você precisa clicar no botão de alternância na parte superior da tela de “Inativo” para “Ativo” e, em seguida, clicar no botão “Salvar snippet”.

Parabéns, você desativou a compactação JPEG em seu site WordPress.

Se você não for um fotógrafo ou artista, provavelmente não verá muita diferença na qualidade. Mas para aqueles que trabalham com imagens de alta qualidade diariamente, a diferença de qualidade é óbvia.

Como aumentar a compactação de imagens no WordPress

Definitivamente, há benefícios de desempenho em deixar a qualidade de compactação como está. Mas, se quiser, você pode alterar o número de 100 para 80 ou algo menor para compactar mais suas imagens e economizar um pouco de espaço.

Basta criar um novo snippet do WPCode, como no método anterior, e colar o código a seguir:

add_filter('jpeg_quality', function($arg){return 75;});
Increasing Image Compression Using WPCode

Quando você ativar o snippet e salvá-lo, suas imagens JPEG serão compactadas para tamanhos de arquivo menores. As imagens serão exibidas com qualidade inferior, mas você economizará espaço em seu servidor da Web.

Dica: Ao fazer essas alterações na qualidade da imagem, certifique-se também de gerar novamente as miniaturas.

Esperamos que este artigo tenha ajudado você a aprender como alterar a compactação de imagens JPEG no WordPress. Talvez você também queira ver nosso guia sobre como adicionar imagens corretamente no WordPress ou nossa seleção especializada dos melhores plug-ins do Instagram para WordPress.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

51 ComentáriosDeixe uma resposta

  1. Syed Balkhi

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Tom

    I tried this so many times, and many different variations of this code but it never works. I don’t know what else to do. Every time I upload a photo, I can see that the quality is blurrier. Do you have any other tips?

      • Tom

        Thanks for the reply. Just an update: It turns out it was my hosting company that was compressing my photos. They had a CDN feature that was automatically enabled that I didn’t know about. After I disabled it, my photos are fine now.

  3. Purnendu Mukherjee

    Hi,
    If we use a image compression plugin like Smush, Optiomole or any other, will my images be compressed twice (once by WordPress and then by the plugin)??

    • WPBeginner Support

      You would want to check with the support for the plugin you plan to use but most should have the ability to cancel the standard compression.

      Administrador

  4. Rigsby

    Hello, once the php is added, will that override any image compression plugin that is installed at a later date or does the plugin override the code? It will be hard to remember that your php was once added a long time ago, and therefore it may cause headaches wondering why the plugin isn’t working correctly.

    Thanks : )

  5. Tom

    ” If you want, you can change the number from 100 to 80 or something lower… then all you have to do is paste the following code:”

    ADD THE CODE WHERE???

  6. rob

    Hi – Do images need to be reuploaded for it to take effect?
    Also, will this work for png images or do I need to change jpeg to png in the php code?
    Thanks

    • WPBeginner Support

      This would only apply to new images and not your current images and you do not have to worry about PNG compression.

      Administrador

  7. Netgoondoo

    Hi, is this code snippet valid in php 7?

    • WPBeginner Support

      The snippet should still be working

      Administrador

  8. puspa chaulagai

    hey, I am from love and fun quotes I found your article while I searching for how to stop auto compressing images on WordPress. I try your code but it still not working. When I change the theme it’s work but in which theme I apply it doesn’t work. How to remove auto image compress by theme please help.

    • WPBeginner Support

      You would want to reach out to the support for your specific theme for them to be able to assist with their specific compression.

      Administrador

  9. Sukanya

    I have not seen much of a difference even after regenerating. Am I missing something?

  10. Heather Wilson

    Hello,

    I am working with wordpress.com – can you do this through the customizing CSS menu, and if so how? I am brand new to coding.

  11. Karlo Gavric

    Even I change compression to 100, my images looks so bad in quality, only if I use full sized (widht 1300+px) is OK, but if I use Large file which is 900px, it is horrible.

    I added code to change compression in functions.php, contacted my theme supplier and hosting support, they don’t have any compressions turned on.

    Any ideas?

    • WPBeginner Support

      Hi Karlo,

      Try deactivating all plugins and switching to a default theme, after that upload a large image and see if that fixes it.

      Administrador

      • Karlo Gavric

        Hi,

        I’ve tried it, but the problem still persists. Tried also just changing a theme with plugins enabled / disabled, no change (?! feeling confused really ?!)

        • nospampls

          you need to set your large file size to a higher image size. wordpress will automatically crop your images…

  12. Anne

    what does this mean

    Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.

    Thank you

    • Eoin

      It means that you need to use an external editor to edit the files because the Wordpress editor is restricted.. There are plugins available for editing theme files through the wordpress admin which you can look up on the Add New Plugin page, otherwize, you need to download your theme files using a FTP software, update the functions.php file and upload it back to the theme folder on the server. If you are not sure about FTP, I would just look for an theme editor plugin so you can do it in the wordpress admin, but make sure to deactivate the plugin when you are finished to prevent any security issues.

  13. Devi Chand

    Hi,

    My product images looked blurred because they are already optimised and wordpress was optimising them again (I believe). I used the above code and also regenerated the thumbnails. Initially, I could not find the changes. However, later the images started showing up the way I wanted (not blurred, perfect) for some time. But I check again and the images are all looking blurred again. Can you help?

  14. Bjornen

    Hi!

    So, is there a solution to having WP not up-scaling the image size (kb/mb) when uploading via “Media” in WordPress?

    Meaning; I want WP to scale the picture into thumb nail, medium and large and to keep the original as it does per default, but NOT to up-scale the thumb ail, medium or large file sizes?

    Thanks!

  15. Mike

    I added this code exactly how you showed it and now it won’t let me upload photos an error message keeps coming up. please help! Thanks!

  16. Yara

    Hi

    Do you know if is possible to improve the quality of the image in wordpress.com in free version?

    Thanks

    • Yara

      Or better, if is possible to do not reduce the quality of the image

      • Yara

        Hi

        Now I have wordpress.org because I was frustated with my images quality. But now it is worst. I did what your video say, but I still have problems.

        I thought that was just upload the image and was OK. My head image and when I upload in the post the quality is not good.

        I really don’t know what to do :/

  17. Mélanie

    Hi, I use this code and regenerated all my images, but unfortunatly, the size of my image is the same. I use enfold theme and my WP version is 4.7.2. Did I miss a step?

    • Mélanie

      I forgot to say, I compressed to 75.

  18. Luke Cavanagh

    Setting the level to 92 or 90 is fine, the default used to be 90 was was lowered down to 82.

  19. Alessandro

    Hi, I have added the code as showed in the video but, nothing, Wordpress keeps reducing the size of my images.

    Any other option?

    Thanks for your support
    Alessandro

  20. Lukas Priyambodo

    Quality 100 doesn’t always mean highest quality, because of JPEG algorithm and what kind of content of the image. Using SSIM, I sometimes found that quality 95 has better score than quality 100 or at least quality 95 has better filesize trade off compare to quality 100.

  21. Jaime

    Hi there. Are you able to disable image compression if you have a free Wordpress account? If so, where do I find my function’s php file?

  22. M.Mairaj

    Thanks for sharing such a fantastic post about image Compression in Wordpress. All the tips are really very very worthwhile.

    Keep sharing :)

    Regards

    Mairaj

  23. Peter

    Don’t follow this advice! I added this line of code in my functions.php file and now I get this message when loading my website!

    Parse error: syntax error, unexpected T_STRING in /home/sittin11/public_html/wp-content/themes/Divi/core/functions.php on line 44

  24. blogmann

    Thanks
    I’m using plugin Imsanity, it has more settings

  25. karl

    Let’s clear up some things.
    1 – WP does not mess with your original uploaded file. The compression levels discussed are for WP generated images – the TN, Med, Large in your WP media settings.

    2 – if you change the compression settings, WP does not reprocess all your current uploads. That’s why you run Regenerate Thumbnails.

    3 – I will challenge any photographer to see the quality difference between 100 and 90 in a JPG. In rare cases, you may. But for 99% of images you’ll never tell.

    4 – Depending on your theme and your media settings, yes, some smaller image sizes will be cropped from your orignal upload. It’s the nature of the beast. If your TN is square and you upload a horizontal phjoto, of course it will be cropped. Cropping your images BEFORE uploading – and using a proportion compatible with your theme layout – will net you fewer issues.

    • Santiago Gonzalez

      Thanks Karl, your comment was very helpfull to clear things up.

      Thanks ;)

  26. chang hong

    hello, can you tellme why wp crop every image that i upload? how can i prevent it! thank you

  27. Dave Porter

    Thanks for the article, very useful to know.

    I’m interested in the comment about ‘make sure you regenerate your thumbnails’

    If an image is uploaded at say 82%, regenerating the thumbnails does what?

    And I assume that after changing the percentage, this is only going to be for new images?
    I would guess any existing images would remain at the same quality, or does WordPress keep a copy of the original uploaded?
    TIA, Dave

  28. Michael

    Is it possible to disable image compression in WordPress?
    The article has a headline saying so, but then it describes it as “least compression”, that is not disabling compression…just wondering it is possible to disable compression for uploaded pictures…

    • karl

      Setting compression to 100 IS disabling it.

  29. Thomas

    Great Tips, thank you.
    I have one more question: If I upload images to WP that are already compressed (say to 90%) – will they be compressed again (82% of 90% = 74.8%)?

    • Stephen

      Yes. The only exception is the image you upload is saved as is for future use.

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.