M -
M -

Reputation: 28472

saving dataURL image locally via php

I'm making a PNG image file from a dataURL string (thanks to the example from The PHP manual). I'd like this code to open the "Download file" dialog in the browser, so users can save this image locally, but calling the function imagepng() saves the image to my server instead. Am I using the wrong function when calling imagepng()? I'm trying to trigger a download by changing the headers, but it's still saving to the server.

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
    . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
    . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
    . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';

$data = base64_decode($data);

$im = imagecreatefromstring($data);

// set the headers, to trigger a download
header('Content-Disposition: attachment; filename="image.png"');
header('Content-Type: image/png');
imagepng($im, 'test_2.png');
imagedestroy($im);
?>

Also, I'm calling the PHP via the following JavaScript, (not sure if this is relevant to the results I'm getting)

$.ajax({ 
    type: "POST", 
    url: "php/downloadimg.php",
    dataType: 'text',
    data: {
        data : finishedImage.src
    }
})

Upvotes: 0

Views: 741

Answers (2)

Telgin
Telgin

Reputation: 1604

It's worth noting that since you've already got the image data in PHP, there's no need to call the imagepng function or anything like it. All you need to do is dump your image data to the client after you set the headers, which will then decide for itself what to do with it.

So, something like this will work if you don't need to actually process the image server side:

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
    . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
    . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
    . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';

$data = base64_decode($data);

// set the headers, to trigger a download
header('Content-Disposition: attachment; filename="image.png"');
header('Content-Type: image/png');

echo $data;
?>

Upvotes: 1

ins0
ins0

Reputation: 3928

just call the imagepng function without the second parameter. if you follow the imagepng documentation you read that filling in the second parameter the image is saved to this filename.

pass only the image resource to the function and the raw image are send to the client.

http://php.net/manual/de/function.imagepng.php

header('Content-Disposition: attachment; filename="image.png"');
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

if you use php only files don't use the php close tag ?> to avoid leaked whitespaces and messed up your output stream.

Upvotes: 1

Related Questions