W
W
whynot2010-12-22 00:00:38
PHP
whynot, 2010-12-22 00:00:38

Base64, imagecreatefromstring and black squares?

Hello. It was necessary to save the intermediate results from the drawn canvas on the server.
One "but" on the saved pictures you need to put a watermark.
I do it like this:

var canvas = document.getElementById('canvas'),
        dataURL = canvas.toDataURL("image/jpeg");
    //отправляю POST-запрос с dataURL

On the server side:
$dataURL = base64_decode(str_replace('data:image/jpeg;base64,', '', $_POST['dataURL']));
        $image = imagecreatefromstring($dataURL);
        ob_start();
        //где-нибудь тут ставлю вотермарк
        imagejpeg($image);
        $filename = 'test.jpeg';
        $binaryImage = ob_get_clean();
        $file = fopen ($filename, 'w');
        fwrite($file, $binaryImage);

And I get a black square. That being said, if I do something like
$dataURL = file_get_contents('1.jpeg');
        $image = imagecreatefromstring($dataURL);
        ob_start();
        //где-нибудь тут ставлю вотермарк
        imagejpeg($image);
        $filename = 'test.jpeg';
        $binaryImage = ob_get_clean();
        $file = fopen ($filename, 'w');
        fwrite($file, $binaryImage);

That's all right. Because of this, there are doubts about, how to put it more correctly, the correct format of the base64 string on the client. The feeling that the canvas produces something incomprehensible to the php imagecreatefromstring();
Nobody came across?
Thank you.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
OlegTar, 2010-12-22
@OlegTar

There is an assumption that not the entire line gets into POST['dataURL'] .
output the base64 string you get in JS.
output the base64 string you get in POST['dataURL']
compare them.

W
webscout, 2010-12-22
@webscout

Checked your script. It doesn't work with image/jpeg. If you encode with javascript in png, then everything is fine.
From this conclusion: the problem is not in base64_decode, the problem is most likely in jpeg encoding by the browser.
If you really need jpeg as an output format, then maybe it's better to convert on the server using the same GD?

O
OlegTar, 2010-12-22
@OlegTar

What browser?
Right now I checked in Chrome. It turns out that if you call the toDataURL('image/ jpeg ');
It outputs image/ png !
Firefox doesn't have this problem.

O
OlegTar, 2010-12-22
@OlegTar

Right now I checked.
In Chrome 8, you can write whatever you want in the toDataURL parameter, even rubbish, it will always return image/png
Firefox 3.6.13 looks at the parameters: if you send a parameter that Firefox does not know in toDataURL, it will not display anything.
So far I have found out that Firefox knows 2 parameters: image/png and image/jpg (neither image/gif nor image/bmp knows)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question