Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Integração Biblioteca WebCAM no Framework Pessoal, bom dia! Consegui organizar uma biblioteca para capturar imagem webcam através do PHP. Esta biblioteca utiliza recursos flash e javascript. Eu preciso da ajuda de vocês para integrar numa página desenvolvida no Adianti Framework. Não sei como mesclar esta biblioteca à tela de cadastro....
PF
Integração Biblioteca WebCAM no Framework  
Pessoal, bom dia!

Consegui organizar uma biblioteca para capturar imagem webcam através do PHP. Esta biblioteca utiliza recursos flash e javascript. Eu preciso da ajuda de vocês para integrar numa página desenvolvida no Adianti Framework. Não sei como mesclar esta biblioteca à tela de cadastro.

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (15)


MG

Me interesso pelo assunto. Acompanhando.
LC

Eu consegui, mais usei o exemplo de um outro post seu:
https://www.adianti.com.br/forum/pt/view_4223?utilizar-webcamjs-para-tirar-fotos

Fiz umas coisas que não sei explicar direito (rsrs), vou tentar resumir, depois coloco aqui.
PF

Valeu! Aguardo o compartilhamento da idéia!
NR

adianti.com.br/framework-extensibility
LC

  1. <?php
  1. <?php
  2. /**
  3.  * WebcamForm Registration
  4.  * @author  Imprime Informática
  5.  */
  6. class WebcamForm extends TPage
  7. {
  8.     protected $form// form
  9.     private $frameFoto;
  10.     private $frameFotoWebCan;
  11.     
  12.     /**
  13.      * Class constructor
  14.      * Creates the page and the registration form
  15.      */
  16.     function __construct()
  17.     {
  18.         parent::__construct();
  19.         
  20.         TPage::include_js('app/lib/components/webcam/webcam.min.js');
  21.         TPage::include_js('app/lib/components/webcam/webcam.nome_seu_arquivo.js');
  22.         // creates the form
  23.         $this->form = new BootstrapFormBuilder('form_Pessoa');
  24.         $this->form->setFormTitle('Pessoa');
  25.         $this->form->setFieldSizes('100%');
  26.         
  27.         // create the form fields
  28.         $id                             = new TEntry('id');
  29.         $datacadastro                   = new TDate('datacadastro');
  30.         $datanascto                     = new TDate('datanascto');
  31.         $fj                             = new TRadioGroup('fj');
  32.         $nome                           = new TEntry('nome');
  33.         $nomefantasia                   = new TEntry('nomefantasia');
  34.         $situacao                       = new TRadioGroup('situacao');
  35.         $situacao->addItems(array('0'=>'Ativo','1'=>'Inativo'));
  36.         $situacao->setLayout('Horizontal');
  37.         $situacao->setValue('0');
  38.         $situacao->setUseButton();
  39.         $nome_arq_foto                  = new TFile('nome_arq_foto');
  40.         $nome_arq_foto->setAllowedExtensions( ['png''jpg'] );
  41.         // complete upload action
  42.         $nome_arq_foto->setCompleteAction( new TAction( array( $this'onCompleteFoto' ) ) );
  43.         // Propriedades dos campos
  44.         $id->setEditable(False);
  45.         $datacadastro->setMask('dd/mm/yyyy');
  46.         $datacadastro->setValuedate('d/m/Y') );
  47.         $datacadastro->setTip('Data de Cadastro');
  48.         $datanascto->setMask('dd/mm/yyyy');
  49.         $fj->addItems(array('1'=>'Física','2'=>'Jurídica'));
  50.         $fj->setLayout('Horizontal');
  51.         $fj->setValue('1');
  52.         $fj->setUseButton();
  53.         $nome->addValidation('Nome/Razão Social', new TRequiredValidator);
  54.         
  55.         $nome_arq_foto->setSize('100%');
  56.         // add one row for each form field
  57.         $row $this->form->addFields( [ new TLabel('ID'), $id ], 
  58.                                        [ new TLabel('Data Cadastro'), $datacadastro ], 
  59.                                        [ new TLabel('Situação'), $situacao], 
  60.                                        [ new TLabel('Data Nascto'),  $datanascto ], 
  61.                                        [ new TLabel('Pessoa'), $fj ] );
  62.         $row->layout = ['col-sm-2''col-sm-3''col-sm-2''col-sm-3''col-sm-2'];
  63.         $label_nome = new TLabel('Nome/Razão Social');
  64.         $row $this->form->addFields( [ $label_nome$nome ], 
  65.                                        [ new TLabel('Nome Fantasia'), $nomefantasia ] );
  66.         $label_nome->setFontColor('#FF0000');
  67.         $row->layout = ['col-sm-6''col-sm-6'];
  68.         $divisor = new TFormSeparator('Foto <span class="fa fa-long-arrow-down" aria-hidden="true"></span>''#333333;margin-bottom:0''18''#000;margin-bottom:0'); 
  69.         $divisor->style 'background-color: #b1d4e8; padding-top: 1px';
  70.         $this->form->addContent( [ $divisor ] );
  71.         // campo para fazer upload de uma imagem qualquer (caso não use a webcam)
  72.         $row $this->form->addFields( [ new TLabel('Foto <b>(PNG ou JPG)</b>'), $nome_arq_foto ] );
  73.         // div onde fica a foto se existir ou a camera apos clicar no botão Acessar Webcam
  74.         $this->frameFoto = new TElement'div' );
  75.         $this->frameFoto->id 'user_foto_frame';
  76.         $this->frameFoto->style '';
  77.         // div onde fica a foto tirada apos clicar no botão Bater Foto
  78.         $this->frameFotoWebCan = new TElement'div' );
  79.         $this->frameFotoWebCan->id 'user_foto_frameWebCam';
  80.         $this->frameFotoWebCan->style '';
  81.         // label que fica acima da div
  82.         $labelframeFotoWebCan = new TLabel('Foto Tirada');
  83.         $labelframeFotoWebCan->id 'labelframeFotoWebCan';
  84.         $labelframeFotoWebCan->style 'display:none';
  85.         
  86.         // botão para acessar a webcam
  87.         $btnWebcam = new TButton('btnWebcam');
  88.         $btnWebcam->addFunction("setup(); $(this).hide(); $( '#labelAcessarWebcam' ).css( 'display', 'none' ); $( '#btnWebcamBaterFoto' ).css( 'display', '' ); $( '#labelWebcamBaterFoto' ).css( 'display', '' )");
  89.         $btnWebcam->setImage('fa:camera');
  90.         $btnWebcam->setLabel('Acessar Webcam');
  91.         $btnWebcamLabel = new TLabel('&nbsp&nbsp');
  92.         $btnWebcamLabel->id 'labelAcessarWebcam';
  93.         // botão para bater a foto
  94.         $btnWebcamBaterFoto = new TButton('btnBaterFoto');
  95.         $btnWebcamBaterFoto->addFunction("take_snapshot(); $( '#labelframeFotoWebCan' ).css( 'display', '' )");
  96.         $btnWebcamBaterFoto->setImage('fa:camera');
  97.         $btnWebcamBaterFoto->id 'btnWebcamBaterFoto';
  98.         $btnWebcamBaterFoto->style 'display:none';
  99.         $btnWebcamBaterFoto->setLabel('Bater Foto');
  100.         $btnWebcamBaterFotoLabel = new TLabel('&nbsp&nbsp');
  101.         $btnWebcamBaterFotoLabel->id 'labelWebcamBaterFoto';
  102.         $btnWebcamBaterFotoLabel->style 'display:none';
  103.         // adiciona os campos no form
  104.         $row $this->form->addContent( [ new TLabel('Formato 300x300 (Recomendado)'), $this->frameFoto ],
  105.                                         [ $labelframeFotoWebCan$this->frameFotoWebCan ],
  106.                                         [ $btnWebcamLabel$btnWebcam ],
  107.                                         [ $btnWebcamBaterFotoLabel$btnWebcamBaterFoto ] );
  108.         $row->layout = ['col-sm-4''col-sm-4''col-sm-2''col-sm-2'];
  109.         // campo text para receber a datauri da foto tirada (uso este campo para gerar/salvar a foto)
  110.         $fotoWebcam = new TText('fotoWebcam');
  111.         $fotoWebcam->id 'idFotoWebcam';
  112.         $fotoWebcam->style 'display:none;';
  113.         $this->form->addFields( [ $fotoWebcam ] );
  114.         // create the form actions
  115.         $btn $this->form->addAction_t('Save'), new TAction([$this'onSave']), 'fa:floppy-o' );
  116.         $btn->class 'btn btn-sm btn-primary';
  117.         $btnNovo $this->form->addAction_t('New'), new TAction([$this'onEdit']), 'fa:eraser red' );
  118.         $this->form->addAction_t('Back to the listing'), new TAction(['PessoasList''onReload']), 'fa:table blue' );
  119.         $this->form->addHeaderAction_t('Save'), new TAction([$this'onSave']), 'fa:save green' );
  120.         $this->form->addHeaderAction_t('Back'), new TAction(['PessoasList''onReload']), 'fa:table blue' );
  121.         // wrap the page content
  122.         $vbox = new TVBox;
  123.         $vbox->style 'width: 98%';
  124.         //$vbox->add(new TXMLBreadCrumb('menu.xml', 'PessoasList'));
  125.         $vbox->add($this->form);
  126.         
  127.         // add the form inside the page
  128.         parent::add($vbox);
  129.     }
  130.     /**
  131.      * On complete upload
  132.      */
  133.     public static function onCompleteFoto$param ) {
  134.         //new TMessage('info', 'Upload completed: '.$param['nome_arq_foto']);
  135.         //var_dump($param);
  136.         // refresh photo_frame
  137.         TScript::create"$('#user_foto_frame').html('')" );
  138.         TScript::create"$('#user_foto_frame').append(\"<img style='max-width: 100%;' src='tmp/{$param'nome_arq_foto' ]}'>\");" );
  139.     }
  140.     /**
  141.      * method onSave()
  142.      * Executed whenever the user clicks at the save button
  143.      */
  144.     public function onSave$param )
  145.     {
  146.         try
  147.         {
  148.             TTransaction::open('db'); // open a transaction
  149.             
  150.             // get the form data into an active record Pessoa
  151.             $object $this->form->getData('Pessoa');
  152.             //var_dump($object);
  153.             //die;
  154.             
  155.             $this->form->validate(); // form validation
  156.             // move a foto para a pasta
  157.             $sourceUserFoto 'tmp/' $object->nome_arq_foto;
  158.             $targetUserFoto 'fotos/' $object->nome_arq_foto;
  159.             $finfoBanner = new finfoFILEINFO_MIME_TYPE );
  160.             //echo $sourceUserFoto . '<br>';
  161.             //echo $targetUserFoto . '<br>';
  162.             // validação do campo logo PNG/JPG
  163.             if ( $object->nome_arq_foto != '' and file_exists$sourceUserFoto ) and $finfoBanner->file$sourceUserFoto ) != 'image/png' and $finfoBanner->file$sourceUserFoto ) != 'image/jpeg' )
  164.             {
  165.                 // excluir arquivo temporario
  166.                 unlink$sourceUserFoto );
  167.                 // limpa o campo
  168.                 $object->nome_arq_foto '';
  169.                 // retorna mensagem de erro
  170.                 throw new Exception'Foto inválida, escolha um arquivo no formato <strong>PNG</strong> ou <strong>JPG</strong> !' );
  171.             }
  172.             // nome fantasia igual ao nome se o fantasia estiver em banco
  173.             if ( empty($object->nomefantasia) ):
  174.                 $object->nomefantasia $object->nome;
  175.             endif;
  176.             // foto webcam
  177.             if ( $object->fotoWebcam != '' )
  178.             {
  179.                 $img $object->fotoWebcam;
  180.                 $img str_replace('data:image/jpeg;base64,'''$img);
  181.                 $img str_replace(' ''+'$img);
  182.                 $data base64_decode($img);
  183.                 //var_dump($data);
  184.                 $f md5(uniqid(rand(), true)) . '_fotowebcam_pessoa.jpg';
  185.                 
  186.                 $success file_put_contents('fotos/' $f$data);
  187.                 
  188.                 if ($success)
  189.                 {
  190.                     $object->nome_arq_foto $f;
  191.                     $targetUserFoto 'fotos/' $object->nome_arq_foto;
  192.                     //var_dump($object->nome_arq_foto);
  193.                 }
  194.                 // limpa o campo
  195.                 $object->fotoWebcam ' ';
  196.             }
  197.             // salva o registro
  198.             //$object->store(); // stores the object
  199.             $this->form->setData($object); // keep form data
  200.     
  201.     
  202.             TTransaction::close(); // close the transaction
  203.                 
  204.             // if the user uploaded a source file
  205.             if ( ($object->nome_arq_foto != '') and file_exists$sourceUserFoto ) and ( $finfoBanner->file$sourceUserFoto ) == 'image/png' or $finfoBanner->file$sourceUserFoto ) == 'image/jpeg') )
  206.             {
  207.                 // redimenciona se a larguda for maior que 800px
  208.                 $img = new Canvas$sourceUserFoto );
  209.                 //var_dump($img);
  210.                 $larg 300;
  211.                 $altu 300;
  212.                 // se tem largura ou altura então redimenciona
  213.                 if ($larg != || $altu != 0):
  214.                     $img->redimensiona$larg$altu'preenchimento' );
  215.                 endif;
  216.                 // grava uma nova imagem com 90% de qualidade da original
  217.                 $img->grava$sourceUserFoto90 );
  218.                 // move to the target directory
  219.                 rename$sourceUserFoto$targetUserFoto );
  220.             }
  221.             // exibe a imagem
  222.             if ( $object->nome_arq_foto != '' ):
  223.                 $image = new TImage$targetUserFoto );
  224.                 $image->style 'max-width: 100%;';
  225.                 $this->frameFoto->clearChildren();
  226.                 $this->frameFoto->add$image );
  227.             endif;
  228.             // neste reload vai colocar os endereços e contatos na tela
  229.             $this->onReload$param ); // reload
  230.             $alert = new TAlert('info',TAdiantiCoreTranslator::translate'Record saved' ));
  231.             $alert->id 'alertOnSave';
  232.             $alert->style 'width: 98%';
  233.             TScript::create"$('#alertOnSave').fadeOut(5000);");
  234.             parent::add$alert );
  235.             // shows the success message
  236.             //new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  237.         }
  238.         catch (Exception $e// in case of exception
  239.         {
  240.             new TMessage('error''<b>Erro</b> ' $e->getMessage()); // shows the exception error message
  241.             $data $this->form->getData();
  242.             $this->form->setData$data ); // keep form data
  243.             if ( $data->nome_arq_foto != '' ): // se existe informação no campo
  244.                 if ( file_exists'tmp/' $data->nome_arq_foto ) ): // se tem arquivo na pasta temporaria
  245.                     $image = new TImage'tmp/' $data->nome_arq_foto );
  246.                     $image->style 'max-width: 100%;';
  247.                     $this->frameFoto->add$image );
  248.                 elseif ( file_exists'fotos/' $data->nome_arq_foto ) ): // se não tem na pasta temporaria, então verifica a pasta padrão
  249.                     $image = new TImage'fotos/' $data->nome_arq_foto );
  250.                     $image->style 'max-width: 100%;';
  251.                     $this->frameFoto->add$image );
  252.                 endif;
  253.             endif;
  254.             // neste reload vai colocar os endereços e contatos na tela
  255.             $this->onReload$param ); // reload
  256.     
  257.             TTransaction::rollback(); // undo all pending operations
  258.         }
  259.     }
  260.     
  261.     /**
  262.      * method onEdit()
  263.      * Executed whenever the user clicks at the edit button da datagrid
  264.      */
  265.     function onEdit($param)
  266.     {
  267.         try
  268.         {
  269.             if (isset($param['key']))
  270.             {
  271.                 $key=$param['key'];  // get the parameter $key
  272.                 TTransaction::open('db'); // open a transaction
  273.                 $object = new Pessoa($key); // instantiates the Active Record
  274.                 
  275.                 $this->form->setData($object); // fill the form
  276.                 
  277.                 // mostra imagem se existir
  278.                 if ( $object->nome_arq_foto ):
  279.                     $image = new TImage'fotos/' $object->nome_arq_foto );
  280.                     $image->style 'max-width: 100%;';
  281.                     $this->frameFoto->add$image );
  282.                 endif;
  283.                 // neste reload vai colocar os endereços na tela
  284.                 $this->onReload$param ); // reload endereços
  285.                 TTransaction::close(); // close the transaction
  286.             }
  287.             else
  288.             {
  289.                 //$this->form->clear();
  290.             }
  291.         }
  292.         catch (Exception $e// in case of exception
  293.         {
  294.             new TMessage('error''<b>Erro</b> ' $e->getMessage()); // shows the exception error message
  295.             TTransaction::rollback(); // undo all pending operations
  296.         }
  297.     }
  298.     
  299.     /**
  300.      * Reload the item list
  301.      * @param $param URL parameters
  302.      */
  303.     public function onReload($param)
  304.     {
  305.         $data $this->form->getData();
  306.         $this->loaded TRUE;
  307.     }
  308.     
  309. }
  310. ?>


conteudo do: webcam.nome_seu_arquivo.js
Webcam.set({ // live preview size width: 380, height: 300, // device capture size dest_width: 380, dest_height: 300, // final cropped size crop_width: 300, crop_height: 300, image_format: 'jpeg', jpeg_quality: 90 }); function setup() { Webcam.reset(); Webcam.attach('#user_foto_frame'); } function take_snapshot() { // take snapshot and get image data Webcam.snap(function (data_uri) { // display results in page document.getElementById('user_foto_frameWebCam').innerHTML = '<img src="' + data_uri + '"/>'; $("textarea[name='fotoWebcam']").val(data_uri); }); }
LC

O arquivo webcam.min.js pode pegar neste link:https://www.adianti.com.br/forum/pt/view_4223?utilizar-webcamjs-para-tirar-fotos
PF

Leandro, valeu a dica e exemplo. Farei a implementação em meu site.
PM

Eu reproduzi o conteudo acima porem ao clicar em acessar a webcam nada acontece, alguem ai conseguiu?
LC

Pedro, inspecione ai e veja se carregou os arquivos js :
<script language="JavaScript" src="app/lib/components/webcam/webcam.min.js"></script> <script language="JavaScript" src="app/lib/components/webcam/webcam.nome_seu_arquivo.js"></script>


Se carregou veja se no inicio do arquivo webcam.min.js esta com essa versão:
// WebcamJS v1.0.24 - http://github.com/jhuckaby/webcamjs - MIT Licensed


Confirme se o conteúdo do webcam.nome_seu_arquivo.js está conforme abaixo:
Webcam.set({ // live preview size width: 380, height: 300, // device capture size dest_width: 380, dest_height: 300, // final cropped size crop_width: 300, crop_height: 300, image_format: 'jpeg', jpeg_quality: 90 }); function setup() { Webcam.reset(); Webcam.attach('#user_foto_frame'); } function take_snapshot() { // take snapshot and get image data Webcam.snap(function (data_uri) { // display results in page document.getElementById('user_foto_frameWebCam').innerHTML = '<img src="' + data_uri + '"/>'; $("textarea[name='fotoWebcam']").val(data_uri); }); }


LC

Pedro, inspecione ai e veja se carregou os arquivos js :
  1. <?php
  2.    <script language="JavaScript" src="app/lib/components/webcam/webcam.min.js"></script>
  3.    <script language="JavaScript" src="app/lib/components/webcam/webcam.nome_seu_arquivo.js"></script>
  4. ?>


Se carregou veja se no inicio do arquivo webcam.min.js esta com essa versão:
// WebcamJS v1.0.24 - http://github.com/jhuckaby/webcamjs - MIT Licensed


Confirme se o conteúdo do webcam.nome_seu_arquivo.js está conforme abaixo:
  1. <?php
  2. Webcam.set({
  3.     // live preview size
  4.     width380,
  5.     height300,
  6.     // device capture size
  7.     dest_width380,
  8.     dest_height300,
  9.     // final cropped size
  10.     crop_width300,
  11.     crop_height300,
  12.     image_format'jpeg',
  13.     jpeg_quality90
  14. });
  15. function setup() {
  16.     Webcam.reset();
  17.     Webcam.attach('#user_foto_frame');
  18. }
  19. function take_snapshot() {
  20.     // take snapshot and get image data
  21.     Webcam.snap(function (data_uri) {
  22.         // display results in page
  23.         document.getElementById('user_foto_frameWebCam').innerHTML '<img src="' data_uri '"/>';
  24.         
  25.         $("textarea[name='fotoWebcam']").val(data_uri);
  26.     });
  27. }
  28. ?>


PM

Agora funcionou! Obrigado!
AC

Muito bom meu caro. Adaptei ao meu código, porém quando eu tento salvar uma imagem via webcam ele perde o endereço da imagem. Observei que a pasta tmp é excluída. Já passou por algo similar?
LC

Alexsandro, aqui comigo funciona normal.

Veja que ai a pasta tmp é usada quando carrega um arquivo usando o campo TFile ($nome_arq_foto).

A imagem vindo pela captura da Webcam não passa pela pasta tmp, ai no exemplo ela vai para uma pasta chamada fotos, neste comando:
  1. <?php
  2. $success file_put_contents('fotos/' $f$data);
  3. ?>
AC

Eu já faço isso meu caro. Estou tentado aqui.
AC

Depois de algumas modificações eu consegui resolver o problema.