0

I am trying to create thumbnails that will be created by server and then outputted to HTML for user of website but it returns wierd code... My function is:

function createthumbnail($n){
    list($width, $height) = getimagesize($n);
    $newheight = 100;
    $ratio = 100/$height;
    $newwidth = $width*$ratio;
    $im = imagecreatetruecolor($newwidth, $newheight);
    switch(exif_imagetype($n)){
    case "jpg":
        $foto_r = imagecreatefromjpg($n);
    break;
    case "png":
        $foto_r = imagecreatefrompng($n);
    break;
    case "bmp":
        $foto_r = imagecreatefromwbmp($n);
    break;
    default:
        $foto_r = imagecreatefromjpeg($n);
    }
    if(!$foto_r){
        $im = imagecreatetruecolor($newwidth, $newheight);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
 imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        imagestring($im, 1, 5, 5, 'Error loading ' . $n, $tc);
    }else{
        imagecopyresampled($im, $foto_r, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagejpeg($im, null, 100);
    }
    return $foto_r;
}

Here is example of the wierd code: Wierd code example

  • 2
    That's not weird code. You just didn't tell the browser what you're printing! You need to send a `Content-Type` header. Put this before `imagejpeg`, `header('Content-Type: image/jpeg');` – Charlotte Dunois Aug 25 '16 at 16:23
  • Then it doesn't print anything. Just picture-like frame on the left top of website... – Adam Opalecký Aug 25 '16 at 16:26
  • That's the picture your code produces. Now go hunting the problem why your function doesn't make a correct thumbnail. :P – Charlotte Dunois Aug 25 '16 at 16:28
  • But I need that function to generate thumbnail right inside the website so when I use this function it prints thumbnail of the picture for example in the middle of the website not only the thumbnail and no website. That is why I make it as function and not php file itself... – Adam Opalecký Aug 25 '16 at 16:31

1 Answers1

1

If I see it right, then your script builds the html for your webpage and the thumbnail in one single run? Probably something like that?

<img src="<?php echo createthumbnail('path_to_the_image.jpeg'); ?>" alt="" />

The thumbnail has to be an extra file, so another php script that generates the image and the image headers.

<img src="generatethumbnail.php?f=path_to_the_image.jpeg" alt="" />

There is also a "dirty" solution to include the image code as base64 directly in your html code Embedding Base64 Images

Example:

<img src="data:image/jpeg;base64,<?php 
echo base64_encode(createthumbnail('path_to_the_image.jpeg')); 
?>" alt="" />

It is not supported by older browser, the images are not cached in the client that way and the loading time for your site increases drastically, because all the thumbnails would be loaded with the code

Community
  • 1
  • 1
Dimitri L.
  • 4,499
  • 1
  • 15
  • 19