4

Is it possible to transform a .jpg, .jpeg or .gif image to .png in php without saving the image in your computer? Something like:

function read_image($filename, $extension) {
    switch($extension) {
        case '.png':
            $image = imagecreatefrompng($filename);
            break;
        case '.jpg': case '.jpeg':
            $unTransformed = imagecreatefromjpeg($filename);
            $image = transform($unTransformed);
            break;
        case '.gif':
            $unTransformed = imagecreatefromgif($filename);
            $image = transform($unTransformed);
            break;
        return $image;
    }
}
function transform($unTransformed) {

    // Some magic here without actually saving the image to your machine when transforming

    return $transformed;
}

I honestly couldn't find an answer for this. Also note that GD is mandatory.

Dragos Rizescu
  • 3,380
  • 5
  • 31
  • 42

2 Answers2

4

Using output buffering and capturing the output of imagepng should work, like this:

function transform($unTransformed) {
    ob_start();
    imagepng($unTransformed);
    $transformed = ob_get_clean();
    return $transformed;
}

Of course, this is assuming you actually want a variable containing a png bytestream of your image file. If the only purpose is to output it anyways, don't bother and do as Marty McVry suggests.

fvu
  • 32,488
  • 6
  • 61
  • 79
2

Directly from the PHP manual: (imagepng()-function, which outputs a PNG image to either the browser or a file)

header('Content-Type: image/png');
$transformed = imagepng($untransformed);

You might encounter a problem sending the headers along, so it's possibly necessary to output the headers somewhere else or transform the stream created by imagepng to a base64-string and display the image like that, depending on the rest of your code.

Marty McVry
  • 2,838
  • 1
  • 17
  • 23