Convertir une image en Canvas HTML5 en PHP
Rédigé par BeHuman
1 commentaire
Classé dans : HTML/CSS/JavaScript, Php

Pour le fun je me suis fait un script PHP qui me converti une image en tableau HTML
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
function genImg($filename, $opacity="1") {
if ( ( preg_match('/.*\.png$/i',$filename) || preg_match('/.*\.jpg$/i',$filename) || preg_match('/.*\.gif$/i',$filename) ) && file_exists($filename) ) {
if (preg_match('/.*\.png$/i',$filename)) {
$im = imagecreatefrompng($filename);
} else if (preg_match('/.*\.jpg$/i',$filename) || preg_match('/.*\.jpeg$/i',$filename) ) {
$im = imagecreatefromjpeg($filename);
} else if (preg_match('/.*\.gif$/i',$filename)) {
$im = imagecreatefromgif($filename);
}
$npx=0;
$size = getimagesize($filename);
$html= "<canvas id='myCanvas' style='border:0px none; width:".$size[0]."px!important;height:".$size[1]."px;' width='".$size[0]."px' height='".$size[1]."px'>Your browser does not support the HTML5 canvas tag.
</canvas><script>var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');";
for ($i=1; $i<=$size[1]-1; $i++) {
for ($ii=1; $ii<=$size[0]-1; $ii++) {
$rgb = imagecolorat($im, $ii, $i);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$html.= "ctx.fillStyle = \"rgba(".$r.",".$g.",".$b.",".$opacity.")\";";
$html.= "ctx.fillRect(".$ii.",".$i.",1,1);";
}
}
$html.= "</script>";
}
return $html;
}
$fl="ex-img2html/php.jpg";
if (file_exists($fl)) {
echo "<u>Image d'origine :</u><br>".
"<img src='".$fl."'><br><br>".
"<u>Image convertie :</u><br>".
genImg($fl);
}
?>
++