开发者

Specific image dimensions generated by PHP

As we know, if we specify width and height attributes in <img /> element, browser can immidiately locate image in rendered layout. It's not a really big boost of speed, but it's really nice optimisation practice.

Ok, but sometimes image has different dimensions. So we 开发者_开发百科can get it by PHP getimagesize() function.

And here is the question, if we don't have specific dimensions is it worthwhile to use PHP? Of course, we have to write additional code, but if we cope with gallery we anyhow use PHP, so in that case it's only 2 lines of code.

What is your opinion?


It depends on what you're trying to do. The benefits of having the dimensions on the <img/> tag are:

  1. Browser knows the space to reserve for the image as it's downloaded. This means your layout won't jump around as the images load.
  2. It saves the browser from performing a reflow and repaint once the images load (speed optimization).
  3. You'll have the dimensions available to any Javascript processing as soon as the HTML is finished loading.

On the other hand, adding the dimensions will increase your page size and cause you to use more bandwidth.


You have to realize that getimagesize causes an I/O read (unless you're doing blob reads from db, then it's okay). So, then you have doubled your I/O reads just for loading images. Computers are generally fast enough that computing width and height of images for browsers, is not really much of an issue.

Then again, you have other venues of optimization:

  • sprites
  • putting assets in CDNs instead of app
  • validate your code

I think generally, it's impractical to implement this, because it creates more inefficiencies that it optimizes.


Well I never bother. And frankly most of the websites don't bother as well. The thing is that browser doesn't need to download the whole image to get it's dimensions. Most of the image formats have the image size in a header of the file. so once browser got first few bytes of the file it already knows what the dimensions are.


Function getimagesize() tries to parse image size from the file every time your PHP is called. So basically instead of one disk seek you have two (plus parsing - if you parse some huge video file instead of image it could be literally seconds).

I personally have a CMS that reads image size only on image upload and then saves it in DB with other data, so no extra disk access is needed. Of course this might be overkill for you - YMMV.

Best advice: test it. It is a simple test and it will give you the most relevant answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜