Tampilkan postingan dengan label HTML5. Tampilkan semua postingan
Tampilkan postingan dengan label HTML5. Tampilkan semua postingan

Minggu, 30 Agustus 2020

Save PNG image from HTML5 Canvas (the correct way, proved working!!)

This post is kind of a continuation of my previous post 'Take A Picture From Webcam With HTML5'. I had then an issue how to save the image localy. The image taken from the webcam is saved in base64 encoded data with this format data:image/png;base64,AAAFBfj....[base64 encoded data]

After I googled around, the most solution that I found told me just seperate the base64 data from that format and decode it directly to save the image. Unfortunately, its not that easy!!!

shortly, I'll show you how to do it correctly. This solution is shown here. Thanks mas bro Fazlurr!! you are the best.

again, I developed the application using Codeigniter and the code I show here is the function to save the image localy. This function is called by an AJAX function. 



function saveImage(){
     $img = str_replace('data:image/png;base64,', '', $_POST['data']);
     $img = str_replace(' ', '+', $img);
     $data = base64_decode($img);
     $file = FCPATH.'/image/page/'.$_POST['name'].'.png';
     $success = file_put_contents($file, $data);
     echo $success ? '1' : '0';
}



the AJAX send  two POST data; the image data taken from canva and the name used for this image. Take a look at the third line, this line is the key. Other solutions found in google don't have this line, so most of them failed to save the image correctly. 

Well, the funny thing is that I know it works but I don't know what does that third line do, so dont ask me why this code works...ehehehe....

Selasa, 14 Juli 2020

Take Picture From Webcam With HTML 5

HTML5 has a super cool feature, that enables us to access the media installed in our PC. During developing a web app, I surprised with two things, which are already wellknown for most people maybe. But for me they are new and its really good to know.

My app has to take pictures and save them as PDF, but those pictures should not be saved. So first thing, here is my code to take pictures from a web using a webcam.

Here are my sources. Sumber 1 dan Sumber 2

HTML

 
<style>
.videoElement {
 width: 400px;
 height: 275px;
 background-color: #666;
    transform: rotateY(180deg);
    -webkit-transform:rotateY(180deg); /* Safari and Chrome */
    -moz-transform:rotateY(180deg); /* Firefox */
}
</style>

<video autoplay="true" id="video-webcam" class="videoElement" style="text-align:center">
   Izinkan untuk Mengakses Webcam untuk Demo
</video>


<img id="snapshot" style="width: 400px;height: 275px;">                          

<button onclick="takeSnapshot()"> Take Picture </button>
                            


And here is the JS code:

 
var video = document.querySelector("#video-webcam");

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

if (navigator.getUserMedia) {
    navigator.getUserMedia({ video: true }, handleVideo, videoError);
}

function handleVideo(stream) {
    video.srcObject = stream;
    //console.log(stream);
}

function videoError(e) {
    // do something
    alert("Izinkan menggunakan webcam untuk demo!")
}

function takeSnapshot() {
    var img = document.getElementById('snapshot');
    var context;
    var width = video.offsetWidth
            , height = video.offsetHeight;

    canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, width, height);

    img.src = canvas.toDataURL('image/png');
    img.style="transform: scaleX(-1);width: 400px;height: 275px";

}


What I learnt from that code are:
  1. The display taken from webcam has to be mirrored, as well as the picture taken. I did it with the CSS above.
  2. The images, that are taken using canva, are saved in Base64 code. This is super cool, furthermore the HTML tag is able to show an image with source of Base64 code. Super cool.... this feature helps me a lot, because I don't have to save the picture in server. What I did was I took this Base64 code and put them in HTML tag, which the HTML code is later converted to PDF file

Thats all, folks

Selasa, 27 September 2016

HTML5 Server Sent Event in Codeigniter

There are many sources describing about SSE in HTML5 and also with the code that can be downloaded. One source that I can recommend to read is this. W3school also describes SSE in a short, simple and clear explanation.

But, there are not many websites that gives tutorial using SSE in Codeigniter. I'm working on a project using Codeigniter that requires SSE to display a dynamic data. It was quite difficult for me at the beginning to implement SSE in MVC-way, since all the codes that I got from some tutorials are not programmed in MVC-way. 

Maybe it is not the best way to implement SSE in Codeigniter, but at least it works. 

At the client side I have a javascript code shown below that allows client to "subscribe" a stream of data from the server. I send JSON data from server.

var source = new EventSource("❬?php echo site_url('c_sse/loaddata');?❭");
    
  source.addEventListener("message", function(e) {
   document.getElementById("status").innerHTML = "MESSAGE";showdata(e);
   }, false);
   
  source.addEventListener("open", function(e) {
   document.getElementById("status").innerHTML = "OPENED";
   }, false);

  source.addEventListener("error", function(e) {
   document.getElementById("status").innerHTML = e.readyState;
   if (e.readyState == EventSource.CLOSED) {
    document.getElementById("status").innerHTML = "CLOSED";
     }
   }, false);
 } else {
  document.getElementById("notSupported").innerHTML = "SSE not Supported";
 }
}
  
function showdata(Jdat)
{
 var data = JSON.parse(Jdat);
   
 document.getElementById("result").innerHTML = data.name;
}
 

The MVC style code is already seen in there. Check the EventSource above, that is the way I call the function "loaddata" inside controller c_sse.php.

At the server side, I started to code from the controller. The function that is responsible for sending the data (for example) called "loaddata". The most important thing of SSE in server side are the first three line with "header" in the code. Those should be placed in this function and they will cause Error if I put those in the Viewer. So, here is how the function "loaddata" looks like.


function loaddata()
{
 header("Content-Type: text/event-stream");
 header("Cache-Control: no-cache");
 header("Connection: keep-alive");
  
 $this-❭load-❭model('m_sse');
 while(true)
 {
  $data['mydata']=$this-❭m_sse-❭compute_dashboard_data();
  $this-❭load-❭view('sse_view_fast',$data);
  sleep(1);
 }
}


m_sse is the model for computing the data. In my case the return's value of the function 'compute_dashboard_data( )' is JSON data.

The one who is responsible to flush the data to Client is the viewer. Wrongly coded in the viewer can make the performance of SSE much slower. Firstly, I'll show the code resulting slow SSE. Oh ya, I forgot to mention the syntax. The real data should be put behind the "data:".

the source code for sse_view_slow.php:

print "data:".$mydata;
ob_flush();
flush();

If you implement that code, you'll have to wait couple seconds or maybe even couple minutes until the data shown.

Better use this code:

sse_view_fast.php

print "data:".$mydata.PHP_EOL;
print PHP_EOL;

ob_end_flush();
flush();

Actually, that is it for the programming. That is how I implement SSE in Codeigniter.