tags:

views:

58

answers:

1

I am trying to generate an image report for a particular items. Every item has a unique item number, which is stored in the variable $pk.

In this, calling up images/$pk.jpg and/or screenshots/$pk.jpg will show the relevant image or screenshot for the current item page. This works fine in the actual page, however not in my popup report.

For one file, I wish to trim it to 800px before outputting, without storing the resultant file.

Additionally, people can upload files, so I am trying to retrieve a list of all files uploaded that end in png, and output each of these to the browser.

Below is my code, however only the html header is output.

What am I doing wrong? Is it a misuse of the imagepng method?

my code:

<?php
if (isset($_GET["pk"])) {
    $pk = $_GET["pk"];
}
$con = mysqli_connect("localhost","user","pass", "db");
if (!$con) {
    echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
    exit;
} {
    echo "<h1>Image report for auction number: ".$pk. "</h1> \n";
    $srcName = 'screenshots/'.$pk.'.png';
    $info = getimageinfo($srcName);
    $src = imagecreatefrompng($srcName);
    $dest = imagecreate($info[0], min($info[1], 800));
    imagecopy($dest, $src, 0, 0, 0, 0, $info[0], min($info[1], 800));
    imagepng($dest);
    imagepng('images/'.$pk.'.png');
    $filesQuery = "SELECT FILENAME FROM FILES WHERE FILENAME LIKE %png%";
    if ($getFiles = $con->prepare($filesQuery)) {
     $getFiles->execute();
     $getFiles->bind_result($FILENAME);
     $files = array();
     while ($getFiles->fetch()) {
      $filename = array(
               'FILENAME' => $FILENAME,
                );
      $files[] = $filename;
     }
    }
    $filesList = '';
    foreach ($files as $filenames) {
     $imagepng($filenames['FILENAME']);
    }
    ;
}
+1  A: 

You cannot mix HTML and PNG output (that is: embed a PNG inside the HTML) as you are trying to do. You need to split this script in two parts.

The first part (e.g. report.php) outputs a list of all the images along with img tags. E.g:

<img src="/thumbnail.php?pk=1234567" />

Then you implement thumbnail.php to output the image (and just the image) along with the appropriate header. E.g:

<?php
$srcName = 'screenshots/'.$_GET['pk'].'.png';
$info = getimageinfo($srcName);
$src = imagecreatefrompng($srcName);
$dest = imagecreate($info[0], min($info[1], 800));
imagecopy($dest, $src, 0, 0, 0, 0, $info[0], min($info[1], 800));

header('Content-type: image/png');
imagepng($dest);
imagedestroy($src);
imagedestroy($dest);
?>

Two remarks on your code:

  1. imagepng() takes an image resource as it's first parameter (a resource, as created with imagecreatefrompng or imagecreate). It does not take a filename as it's first parameter.
  2. Always destroy the images you created with imagedestroy() or you will run out of memory over time (requiring a restart of your webserver).
Sander Marechal