简体   繁体   中英

How can I gzip images without using .htaccess?

Godaddy won't enable mod_gzip for me, so I have to use headers like this:

<?php 
ob_start ("ob_gzhandler");
header("Content-type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
$offset = 60 * 60 * 24 * 7;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
?>

In this case, that would be for CSS files

Anyways, how can I use that with my images? I mean, making the image: image.php and putting that code at the top but using header("Content-type: image/png; charset: UTF-8"); doesn't work so, let me know.

GZipping images is not worth it. The shrinkage is minuscule or even negative, because image formats do a pretty optimal job compressing already. Try zipping a JPG file to see what I mean.

Also, compressing data that is hard to compress is extremely processor intensive and you may end up using more resources rather than less.

The Yahoo performance rules confirm this:

Image and PDF files should not be gzipped because they are already compressed. Trying to gzip them not only wastes CPU but can potentially increase file sizes.

also, remember that when doing compression in PHP, a PHP process is started every time a request comes in. You could be better off not compressing static resources at all (unless you're paying a lot of money for traffic). Compression should generally be the web server's job, not PHP's.

In general, gzipping GIF,PNG or JPEG images will not yield gains over a couple percent (in fact, the "compressed" file may be larger than the original). If you really want to do that in plain php, use mod_rewrite(or modified image URLs) to redirect the URLs to a php script. Then, outputting the image like

<?php
header('Content-Type:image/png');
echo file_get_contents('img.php');

does work (in your experiments, you have probably inadvertently added spaces into a binary PNG image and thereby broken it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM