1

I'm building a little site at the moment and users can upload their own profile picture but obviously some users pictures will be png and some jpeg, does anyone know anyway to be able to accept both when using the images as a background image in css. Here is my HTML:

<div class='avatar' style='background-image: url('users/avatars/$username.jpg')'></div>

Inside the users/avatars/ folder is every users profile picture named like so: "username.jpg" or "username.png".

Here is an example of my issue: http://cl.ly/image/3W311S2v0v0t

The first post loads the users profile image because it is a jpeg but the second post hasn't loaded the profile image as it is a png.

Thanks in advance.

user3479267
  • 202
  • 9
  • 32

2 Answers2

5

You can do it in CSS like this:

background-image: url('users/avatars/$username.jpg'), url('users/avatars/$username.png');
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28
1

If you absolutely must keep all the logic on the client side, in Javascript, you can catch the error if the image fails to load and attempt to load the other version.

For example:

<div class='avatar'>
 <img src="users/avatars/$username.jpg" onerror='this.src="users/avatars/$username.png";' />
</div>

So if the JPG is not found and returns an error, the image will then load the PNG version.

If you are using PHP you can check the file extension and serve up different HTML. Here's how to read the file extension:

How to get the file extension in PHP?

Community
  • 1
  • 1
Scott
  • 3,736
  • 2
  • 26
  • 44