Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 14
  1. #1

    Upload immegine da <canvas>

    Sto lavorando sulla realizzazione dei "poster" per i video.
    Sono riuscito a salvare il frame che mi interessa tramite <canvas>

    Tutto questo avviene durante la preparazione per l'upload di un video.
    Quindi:
    - l'utente seleziona il video da caricare su server
    - appena viene selezionato si crea l'immagine "poster"

    A questo punto devo inviare al server sia video che immagine (che avranno lo stesso nome)


    Ora ho il problema di come inviare sul server l'immagine che è in memoria visto che non è un file fisico.

    Spero di essermi spiegato.

  2. #2
    Utente di HTML.it L'avatar di vic53
    Registrato dal
    Oct 2010
    residenza
    Fonte Nuova (Roma)
    Messaggi
    588
    Sei stato chiarissimo... Primo punto l'immagine che hai davanti nel browser e' sul pc client...
    la prima cosa che devi fare è salvare l'immagine Canvas in una stringa
    Poi con una routine locale devi fare l'upload sul serve dell'immagine salvata. in questa operazione gli puoi anche cambiare il nome di arrivo....
    Ora come si fa? E come hai intenzione di farlo tu? Per esempio un bottone sul form che salva l'immagine
    Allora per iniziare e studiare la cosa dato che devi scrivere tu il tuo programma pero' ti posto l'esempio che segue che è funzionante... e da qui puoi partire a studiarti la cosa...
    Il programma è stato preso da web e l'ho chiamato SaveCanvas.asp
    e l'include che segue canvas2image.js
    1.mo file SaveCanvas.asp
    codice:
    <!doctype html>
    <html>
    <meta charset="utf-8" />
    <script src="canvas2image.js"></script>
    <style>
        .doc {
            width: 604px;
            margin: 0 auto;
        }
        canvas {
            display: block;
            border: 2px solid #888;
        }
    </style>
    <body>
    <div class="doc">
        <canvas width="600" height="400" id="cvs"></canvas>
        <div>
            <p>
                <button id="save">save</button> or <button id="convert">convert to</button> as: 
                <select id="sel">
                    <option value="png">png</option>
                    <option value="jpeg">jpeg</option>
                    <option value="bmp">bmp</option>
                </select><br/>
                width : <input type="number" value="300" id="imgW" /><br/>
                height : <input type="number" value="200" id="imgH" />
            </p>
    
        </div>
        <div id="imgs">
            
        </div>
    </div>
    <script>
        var canvas, ctx, bMouseIsDown = false, iLastX, iLastY,
            $save, $imgs,
            $convert, $imgW, $imgH,
            $sel;
        function init () {
            canvas = document.getElementById('cvs');
            ctx = canvas.getContext('2d');
            $save = document.getElementById('save');
            $convert = document.getElementById('convert');
            $sel = document.getElementById('sel');
            $imgs = document.getElementById('imgs');
            $imgW = document.getElementById('imgW');
            $imgH = document.getElementById('imgH');
            bind();
            draw();
        }
        function bind () {
            canvas.onmousedown = function(e) {
                bMouseIsDown = true;
                 iLastX = e.clientX - canvas.offsetLeft +  (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
                 iLastY = e.clientY - canvas.offsetTop +  (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
            }
            canvas.onmouseup = function() {
                bMouseIsDown = false;
                iLastX = -1;
                iLastY = -1;
            }
            canvas.onmousemove = function(e) {
                if (bMouseIsDown) {
                     var iX = e.clientX - canvas.offsetLeft +  (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
                     var iY = e.clientY - canvas.offsetTop +  (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
                    ctx.moveTo(iLastX, iLastY);
                    ctx.lineTo(iX, iY);
                    ctx.stroke();
                    iLastX = iX;
                    iLastY = iY;
                }
            };
            
            $save.onclick = function (e) {
                var type = $sel.value,
                    w = $imgW.value,
                    h = $imgH.value;
                Canvas2Image.saveAsImage(canvas, w, h, type);
            }
            $convert.onclick = function (e) {
                var type = $sel.value,
                    w = $imgW.value,
                    h = $imgH.value;
                $imgs.appendChild(Canvas2Image.convertToImage(canvas, w, h, type))
            }
            
        }
        function draw () {
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, 600, 400);
            ctx.fillStyle = 'red';
            ctx.fillRect(100, 100, 50, 50);
        }
        
        
        onload = init;
    </script>
    </body>
    </html>

    poi mando il secondo file a seguire
    Vic53

  3. #3
    Utente di HTML.it L'avatar di vic53
    Registrato dal
    Oct 2010
    residenza
    Fonte Nuova (Roma)
    Messaggi
    588
    2.ndo file canvas2Image.js
    codice:
    /**
     * covert canvas to image
     * and save the image file
     */
    
    var Canvas2Image = function () {
    
        // check if support sth.
        var $support = function () {
            var canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');
    
            return {
                canvas: !!ctx,
                imageData: !!ctx.getImageData,
                dataURL: !!canvas.toDataURL,
                btoa: !!window.btoa
            };
        }();
    
        var downloadMime = 'image/octet-stream';
    
        function scaleCanvas (canvas, width, height) {
            var w = canvas.width,
                h = canvas.height;
            if (width == undefined) {
                width = w;
            }
            if (height == undefined) {
                height = h;
            }
    
            var retCanvas = document.createElement('canvas');
            var retCtx = retCanvas.getContext('2d');
            retCanvas.width = width;
            retCanvas.height = height;
            retCtx.drawImage(canvas, 0, 0, w, h, 0, 0, width, height);
            return retCanvas;
        }
    
        function getDataURL (canvas, type, width, height) {
            canvas = scaleCanvas(canvas, width, height);
            return canvas.toDataURL(type);
        }
    
        function saveFile (strData) {
            document.location.href = strData;
        }
    
        function genImage(strData) {
            var img = document.createElement('img');
            img.src = strData;
            return img;
        }
        function fixType (type) {
            type = type.toLowerCase().replace(/jpg/i, 'jpeg');
            var r = type.match(/png|jpeg|bmp|gif/)[0];
            return 'image/' + r;
        }
        function encodeData (data) {
            if (!window.btoa) { throw 'btoa undefined' }
            var str = '';
            if (typeof data == 'string') {
                str = data;
            } else {
                for (var i = 0; i < data.length; i ++) {
                    str += String.fromCharCode(data[i]);
                }
            }
    
            return btoa(str);
        }
        function getImageData (canvas) {
            var w = canvas.width,
                h = canvas.height;
            return canvas.getContext('2d').getImageData(0, 0, w, h);
        }
        function makeURI (strData, type) {
            return 'data:' + type + ';base64,' + strData;
        }
    
    
        /**
         * create bitmap image
         * 按照规则生æˆå›¾ç‰‡å“应头和å“应体
         */
        var genBitmapImage = function (oData) {
    
            //
            // BITMAPFILEHEADER: http://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
            // BITMAPINFOHEADER: http://msdn.microsoft.com/en-us/library/dd183376.aspx
            //
    
            var biWidth  = oData.width;
            var biHeight    = oData.height;
            var biSizeImage = biWidth * biHeight * 3;
            var bfSize  = biSizeImage + 54; // total header size = 54 bytes
    
            //
            //  typedef struct tagBITMAPFILEHEADER {
            //      WORD bfType;
            //      DWORD bfSize;
            //      WORD bfReserved1;
            //      WORD bfReserved2;
            //      DWORD bfOffBits;
            //  } BITMAPFILEHEADER;
            //
            var BITMAPFILEHEADER = [
                // WORD bfType -- The file type signature; must be "BM"
                0x42, 0x4D,
                // DWORD bfSize -- The size, in bytes, of the bitmap file
                bfSize & 0xff, bfSize >> 8 & 0xff, bfSize >> 16 & 0xff, bfSize >> 24 & 0xff,
                // WORD bfReserved1 -- Reserved; must be zero
                0, 0,
                // WORD bfReserved2 -- Reserved; must be zero
                0, 0,
                // DWORD bfOffBits -- The offset, in bytes, from the beginning of the BITMAPFILEHEADER structure to the bitmap bits.
                54, 0, 0, 0
            ];
    
            //
            //  typedef struct tagBITMAPINFOHEADER {
            //      DWORD biSize;
            //      LONG  biWidth;
            //      LONG  biHeight;
            //      WORD  biPlanes;
            //      WORD  biBitCount;
            //      DWORD biCompression;
            //      DWORD biSizeImage;
            //      LONG  biXPelsPerMeter;
            //      LONG  biYPelsPerMeter;
            //      DWORD biClrUsed;
            //      DWORD biClrImportant;
            //  } BITMAPINFOHEADER, *PBITMAPINFOHEADER;
            //
            var BITMAPINFOHEADER = [
                // DWORD biSize -- The number of bytes required by the structure
                40, 0, 0, 0,
                // LONG biWidth -- The width of the bitmap, in pixels
                biWidth & 0xff, biWidth >> 8 & 0xff, biWidth >> 16 & 0xff, biWidth >> 24 & 0xff,
                // LONG biHeight -- The height of the bitmap, in pixels
                biHeight & 0xff, biHeight >> 8  & 0xff, biHeight >> 16 & 0xff, biHeight >> 24 & 0xff,
                // WORD biPlanes -- The number of planes for the target device. This value must be set to 1
                1, 0,
                // WORD biBitCount -- The number of bits-per-pixel, 24 bits-per-pixel -- the bitmap
                // has a maximum of 2^24 colors (16777216, Truecolor)
                24, 0,
                // DWORD biCompression -- The type of compression, BI_RGB (code 0) -- uncompressed
                0, 0, 0, 0,
                // DWORD biSizeImage -- The size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps
                biSizeImage & 0xff, biSizeImage >> 8 & 0xff, biSizeImage >> 16 & 0xff, biSizeImage >> 24 & 0xff,
                // LONG biXPelsPerMeter, unused
                0,0,0,0,
                // LONG biYPelsPerMeter, unused
                0,0,0,0,
                // DWORD biClrUsed, the number of color indexes of palette, unused
                0,0,0,0,
                // DWORD biClrImportant, unused
                0,0,0,0
            ];
    
            var iPadding = (4 - ((biWidth * 3) % 4)) % 4;
    
            var aImgData = oData.data;
    
            var strPixelData = '';
            var biWidth4 = biWidth<<2;
            var y = biHeight;
            var fromCharCode = String.fromCharCode;
    
            do {
                var iOffsetY = biWidth4*(y-1);
                var strPixelRow = '';
                for (var x = 0; x < biWidth; x++) {
                    var iOffsetX = x<<2;
                    strPixelRow += fromCharCode(aImgData[iOffsetY+iOffsetX+2]) +
                                   fromCharCode(aImgData[iOffsetY+iOffsetX+1]) +
                                   fromCharCode(aImgData[iOffsetY+iOffsetX]);
                }
    
                for (var c = 0; c < iPadding; c++) {
                    strPixelRow += String.fromCharCode(0);
                }
    
                strPixelData += strPixelRow;
            } while (--y);
    
            var strEncoded = encodeData(BITMAPFILEHEADER.concat(BITMAPINFOHEADER)) + encodeData(strPixelData);
    
            return strEncoded;
        };
    
        /**
         * saveAsImage
         * @param canvasElement
         * @param {String} image type
         * @param {Number} [optional] png width
         * @param {Number} [optional] png height
         */
        var saveAsImage = function (canvas, width, height, type) {
            if ($support.canvas && $support.dataURL) {
                if (typeof canvas == "string") { canvas = document.getElementById(canvas); }
                if (type == undefined) { type = 'png'; }
                type = fixType(type);
                if (/bmp/.test(type)) {
                    var data = getImageData(scaleCanvas(canvas, width, height));
                    var strData = genBitmapImage(data);
                    saveFile(makeURI(strData, downloadMime));
                } else {
                    var strData = getDataURL(canvas, type, width, height);
                    saveFile(strData.replace(type, downloadMime));
                }
            }
        };
    
        var convertToImage = function (canvas, width, height, type) {
            if ($support.canvas && $support.dataURL) {
                if (typeof canvas == "string") { canvas = document.getElementById(canvas); }
                if (type == undefined) { type = 'png'; }
                type = fixType(type);
    
                if (/bmp/.test(type)) {
                    var data = getImageData(scaleCanvas(canvas, width, height));
                    var strData = genBitmapImage(data);
                    return genImage(makeURI(strData, 'image/bmp'));
                } else {
                    var strData = getDataURL(canvas, type, width, height);
                    return genImage(strData);
                }
            }
        };
    
    
    
        return {
            saveAsImage: saveAsImage,
            saveAsPNG: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'png');
            },
            saveAsJPEG: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'jpeg');
            },
            saveAsGIF: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'gif');
            },
            saveAsBMP: function (canvas, width, height) {
                return saveAsImage(canvas, width, height, 'bmp');
            },
    
            convertToImage: convertToImage,
            convertToPNG: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'png');
            },
            convertToJPEG: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'jpeg');
            },
            convertToGIF: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'gif');
            },
            convertToBMP: function (canvas, width, height) {
                return convertToImage(canvas, width, height, 'bmp');
            }
        };
    
    }();
    ora puoi studiarci su sulla funzione save e ne parliamo ancora
    ciaoi
    Vic53

  4. #4
    Utente di HTML.it L'avatar di vic53
    Registrato dal
    Oct 2010
    residenza
    Fonte Nuova (Roma)
    Messaggi
    588
    Naturalmente le routine non sono mie ma sono state prese da internet da altri autori che ringraziamo.
    Vic53

  5. #5
    il mio problema non era come catturarla ma come upparla. Ho risolto.
    Carico il video sul server con aspupload
    terminato il caricamento eseguo un js che mi posiziona il video al centro del tempo e catturo l'immagine che poi salvo cul server.

    Sono state necessarie poche righe di programma sia js che asp
    Ultima modifica di SoloWiFi; 10-10-2017 a 20:06

  6. #6
    Utente di HTML.it L'avatar di vic53
    Registrato dal
    Oct 2010
    residenza
    Fonte Nuova (Roma)
    Messaggi
    588
    non essere cosi generico, devi scrivere come hai risolto materialmente ... altrimenti il forum funziona solo per te e non per gli altri che leggono ...
    grazie
    Vic53

  7. #7
    Tranquillo. Domani spiego bene.
    Ora sono col cellulo

  8. #8
    Utente di HTML.it L'avatar di vic53
    Registrato dal
    Oct 2010
    residenza
    Fonte Nuova (Roma)
    Messaggi
    588
    Quote Originariamente inviata da SoloWiFi Visualizza il messaggio
    Tranquillo. Domani spiego bene.
    Ora sono col cellulo
    grazie,
    perche' la cosa che hai messo in evidenza è interessante e mi interessa come soluzione...penso interessi anche a molti altri...

    ciao
    Vic53

  9. #9
    Amministratore L'avatar di Vincent.Zeno
    Registrato dal
    May 2003
    residenza
    Emilia-Romagna (tortellini und cappelletti land!)
    Messaggi
    20,649
    Quote Originariamente inviata da vic53 Visualizza il messaggio
    ...penso interessi anche a molti altri...

  10. #10
    Ecco la mia soluzione:
    Come si vedrà non ho assolutamente fatto uso di jquery o altre librerie che io considero assolutamente inutili, appesantiscono le esecuzioni e rendono il sorgente mal leggibile.
    Qui è tutto puro HTML,Javascript e ASP
    In questo modo è ben comprensibile e poi ognuno se lo arricchisce a piacere.

    Iniziamo con la parte essenziale lato Client
    codice:
    <!-- il video da cui deve essere catturato un frame -->
    <video id="MioVideo"  src="MyVideo.mp4"  type='video/mp4' controls preload="auto"></video>
    <!-- bottone che avvia la cattura -->
    <button class="btn btn-default ButtonPrev" onClick="GrabPoster('MioVideo')">CATTURA</button>
    
    <!-- div con oggetto canvas usato per la cattura. Div hidden -->
    <div style="display:none;">
     <canvas id="PosterCanvas"></canvas>
     <video id="PosterVideo" controls preload="auto" src='' type='video/mp4'></video>
    </div>
    <!-- form che invia al server l'immagine da salvare -->
    <form id="FormPoster" action="UploadPoster.asp" method="post">
     <input type="hidden" name="PostImg" id="PostImg" value="">
     <input type="hidden" name="PostNome" id="PostNome" value="">
    </form>
    <script>
    function GrabPoster(IdVideo) {
     // funzione per catturare e calibrare l'immagine
     var video = document.getElementById(IdVideo);
     var canvas = document.getElementById('PosterCanvas');
     var context = canvas.getContext('2d'); 
     var ratio = (video.videoWidth / video.videoHeight); 
     var w = 320; //video.videoWidth; 
     var h = parseInt(w / ratio, 10); 
      
     canvas.width = w;
     canvas.height = h;
     context.fillRect(0, 0, w, h); 
     context.drawImage(video,0,0,w,h); 
     
     var MyPoster=canvas.toDataURL();  
     document.getElementById("PosterImg").src=MyPoster;
     document.getElementById("DivPosterImg").style.display='';
     
     var NomeCompleto=document.getElementById(IdVideo).src;
     OnlyNome=NomeCompleto.substr(NomeCompleto.lastIndexOf("/")+1); // rimuove path
     OnlyNome=OnlyNome.substr(0,OnlyNome.lastIndexOf("."))+".jpg"; // sostituisce estenzione
     SavePoster(MyPoster,OnlyNome); // richiama funzione per l'invio al server
    }
    function SavePoster(Poster,Nome) {
     // funzione per l'invio al server
     document.getElementById('PostImg').value=Poster;
     document.getElementById('PostNome').value=Nome;
     document.getElementById('FormPoster').submit();
    }
    </script>
    L'operatore deve avviare il video caricato e metterlo in pausa al frame desiderato.
    Successivamente premere il bottone CATTURA.
    Il controllo passa alla funzione GrabPoster che cattura il frame e richiama la funzione SavePoster per inviare al server.
    Molto semplice e sintetico.


    Ora passiamo al lato Server che deve ricevere l'immagine in formato stringa, riconvertire in immagine e salvare su disco.


    codice:
     Poster=request.Form("PostImg")
     Nome=request.Form("PostNome")
     PATH_IMAGES="../public/posters/"
     
     
     Set Doc = Server.CreateObject("MSXML2.DomDocument")
     Set nodeB64 = Doc.CreateElement("b64")
     nodeB64.DataType = "bin.base64"
     nodeB64.Text = Mid(Poster, InStr(Poster, ",") + 1)
     
     dim bStream
     set bStream = server.CreateObject("ADODB.stream")
     bStream.type =  1
     bStream.Open()
     bStream.Write( nodeB64.NodeTypedValue )
     call bStream.SaveToFile(Server.Mappath(PATH_IMAGES&Nome), 2 )
     bStream.close()
     set bStream = nothing
    Anche qui semplice e minimale.


    Ora, portando avanti questo progetto mi sono scontrato con altre necessità e difficoltà:
    1- Cattura diretta in fase di Upload del video
    2- Definire l'orientamento dei video per i browser che non riescono a leggerlo.

    Per il primo caso ho risolto creando questo processo subito dopo l'upload e funziona bene ma solo su computer. Non è possibile con gli smartphone in quanto è bloccato il preload o l'autoload del video

    Per il secondo punto ... ancora non so come fare. Dovrei mettere mano sui meta-tag del video ... almeno credo.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.