<img id='imgt' src='01.jpg' alt='img'>
this image is in original 4000x3000px
- 0.9MB
- computed by css on 960x540px
js
var img = document.getElementById("imgt");
c1 = document.createElement("canvas");
var ctx = c1.getContext("2d");
var a = $('#imgt').width();
var b = $('#imgt').height();
c1.width = a;
c1.height = b;
ctx.drawImage(img, 0, 0, a, b);
var dataURL = c1.toDataURL();
$.ajax({
url: 'process.php',
type: 'post',
data: {'imgBase64': dataURL},
success: function(data) {
console.log('ok');
}
});
process.php
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = 'photo.jpg';
file_put_contents($fileName, $fileData);
Starting image imgt
is 4000x3000px
- 0.9MB
. Resulting image photo.jpg
is 960x540px
- 1.05MB
I suspect that the resulting image is not jpg
but png
in fact, so I tried in js instead of var dataURL = c1.toDataURL()
:
var dataURL = c1.toDataURL("image/jpeg");
also
var dataURL = c1.toDataURL("image/jpeg", 0.95);
In both cases resulting image is about 200KB but not readable in img viewer - it reports damaged image or something like that.
Any help?