Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it
    Registrato dal
    Jul 2022
    Messaggi
    8

    upload immagini da form dopo averle ridimensionate

    Ciao a tutti! spero di essere nella sezione giusta. Il mio intento sarebbe quello di fare un upload di immagini tramite <form id="uploadForm" method="POST" enctype="multipart/form-data">, ma solo dopo che il browser ha provveduto a ridimensionarle.
    Il codice che ho trovato arriva fino al ridimensionamento, ma al punto di inviare l'immagine ridimensionata alla miapagina.php non funziona più. Cliccando sul pulsante SUBMIT non si muove nulla...
    Potreste almeno verificare se a voi funziona?

    l codice è questo:

    parte HTML
    codice HTML:
    <form id="uploadForm">    
    <!-- Input file per la selezione -->    
    <input type="file" id="imageInput" accept="image/*">    
    <br><br>       
    <!-- Anteprima Canvas (nascosta o visibile, opzionale) -->    
    <canvas id="previewCanvas" style="display:none;"></canvas>    
    <img id="previewImg" src="" alt="Anteprima" style="max-width: 300px; display:none;">       
    <br><br>    
    <button type="submit">Invia Immagine Ridotta</button></form>


    parte javascript
    codice:
    const imageInput = document.getElementById('imageInput');
    const previewImg = document.getElementById('previewImg');
    const canvas = document.getElementById('previewCanvas');
    const ctx = canvas.getContext('2d');
    const form = document.getElementById('uploadForm');
    
    
    // Impostazioni larghezza desiderata per l'anteprima/upload
    const MAX_WIDTH = 800;
    
    
    imageInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
    
    
        const reader = new FileReader();
        reader.onload = function(event) {
            const img = new Image();
            img.onload = function() {
                // Calcolo proporzioni per il ridimensionamento
                let width = img.width;
                let height = img.height;
    
    
                if (width > MAX_WIDTH) {
                    height = (MAX_WIDTH / width) * height;
                    width = MAX_WIDTH;
                }
    
    
                // Imposta dimensioni canvas e disegna
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
    
    
                // Mostra anteprima
                const dataUrl = canvas.toDataURL('image/jpeg', 0.8);
                previewImg.src = dataUrl;
                previewImg.style.display = 'block';
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(file);
    });
    
    
    // Invio del form via POST
    form.addEventListener('submit', function(e) {
        e.preventDefault();
    
    
        // Converti canvas in Blob (più efficiente di base64 per l'invio)
        canvas.toBlob(function(blob) {
            const formData = new FormData();
            formData.append('image', blob, 'image.jpg');
    
    
            // Invio AJAX
            fetch('miapagina.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Errore:', error));
    
    
        }, 'image/jpeg', 0.8); // Formato e qualità (0.0 - 1.0)
    });

  2. #2
    Utente di HTML.it L'avatar di abellos
    Registrato dal
    Feb 2002
    Messaggi
    438
    Ciao,
    ho provato il tuo codice, a me da errore sulla riga

    const ctx = canvas.getContext('2d');

    Uncaught TypeError: Cannot read properties of null (reading 'getContext')

    sia con edge che con firefox
    Da un grande potere derivano grandi responsabilità

Tag per questa discussione

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 © 2026 vBulletin Solutions, Inc. All rights reserved.