Adam Opalecký
Adam Opalecký

Reputation: 55

PHP - ImageCreateFromJPEG() return weird code

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

Upvotes: 0

Views: 318

Answers (1)

Dimitri Lavrenük
Dimitri Lavrenük

Reputation: 4879

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

Upvotes: 1

Related Questions