Get jpg png and gif pictures

I have script showing profile pictures of users from my site but it’s hardcoded to only show jpg, problem is that users can upload png and gif as well and when that happens their picture is not displayed, how can I fix this, not changing this line too much as it’s part of the bigger thing and it can’t be all reworked just for this one line?

$imgurl =$_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . "/files/pictures/picture-" . ($user_id) . ".jpg";

I think the correct approach to this problem would be to use something like createimagefrompng to convert uploaded images to jpg. This would keep everything consistent.

However, if you can’t do that then a more hacky approach would be to check if the file exists as a jpg, then png, then gif…so that line above would be turned into something like:

$path = $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . "/files/pictures/picture-" . ($user_id);

if (file_exists($path . ".jpg")) $imgurl = $path. ".jpg";
elseif (file_exists($path . ".png")) $imgurl = $path. ".png";
elseif (file_exists($path . ".gif")) $imgurl = $path. ".gif";
else $imgurl = '404.jpg'

I don’t recommend that though because you would be creating lots of unnecessary requests which will slow down your page.

1 Like

Well I think we’re close here but there’s no need for the last bit as I have default pic for users, perhaps I should’ve included the whole piece of the code responsible for showing the pic.

 function get_avatar($image, $user_id, $account) 
   $imgurl =$_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . "/files/pictures/picture-" . ($user_id) . ".jpg";

   if (!is_imgurl_good($imgurl)) {
     $imgurl =$_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . "/sites/all/themes/simple_custom/user.png";
   return $imgurl;

Another quick hacky “fix” would be to prevent them from uploading anything other than .jpg files, if the site can only display profile pictures in that format. Really, whoever added the upload code should be anticipated the situation, knowing that the output is a particular format. As labofoz said above, you could just convert them during the upload process, too.

Yes I agree but it’s a drupal site and this code is in totally separate chat it’s not even a module, it just gets profile pics to display in chat.

Asc for image MIME-type e.g. with and use required creating function.

1 Like