upload + resize + crop

frenkytribe

Utente Attivo
17 Gen 2013
87
0
0
Buongiorno,
mi sto imbattendo nel realizzare un form di upload in php e jquery e diciamo che tutto per adesso va bene tranne una cosa che secondo me è una sciocchezza ma che comunque non riesco a venirne a capo.
Vi spiego:
in pratica quando eseguo l' upload dell' immagine, subito mi viene stampata a video una preview temporanea dove andrò lì a ritagliare a mio piacimento l' immagine per poi salvarne la miniatura. Questa preview però, se inserisco file jpg ad alta risoluzione me le fa vedere a dimensione naturale, quindi troppo grandi per la pagina. Il codice è il seguente:
Index.php
PHP:
<?php
function uploadImageFile() { // Note: GD library is required for this function

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $iWidth = $iHeight = 100; // desired image result dimensions
        $iJpgQuality = 90;

        if ($_FILES) {

            // if no errors and size less than 250kb
            if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 55555250 * 1024) {
                if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {

                    // new unique filename
                    $sTempFileName = 'cache/' . md5(time().rand());

                    // move uploaded file into cache folder
                    move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);

                    // change file permission to 644
                    @chmod($sTempFileName, 0644);

                    if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
                        $aSize = getimagesize($sTempFileName); // try to obtain image info
                        if (!$aSize) {
                            @unlink($sTempFileName);
                            return;
                        }

                        // check for image type
                        switch($aSize[2]) {
                            case IMAGETYPE_JPEG:
                                $sExt = '.jpg';

                                // create a new image from file 
                                $vImg = @imagecreatefromjpeg($sTempFileName);
                                break;
                            /*case IMAGETYPE_GIF:
                                $sExt = '.gif';

                                // create a new image from file 
                                $vImg = @imagecreatefromgif($sTempFileName);
                                break;*/
                            case IMAGETYPE_PNG:
                                $sExt = '.png';

                                // create a new image from file 
                                $vImg = @imagecreatefrompng($sTempFileName);
                                break;
                            default:
                                @unlink($sTempFileName);
                                return;
                        }

                        // create a new true color image
                        $vDstImg = @imagecreatetruecolor( $iWidth, $iHeight );

                        // copy and resize part of an image with resampling
                        imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);

                        // define a result image filename
                        $sResultFileName = $sTempFileName . $sExt;

                        // output image to file
                        imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
                        @unlink($sTempFileName);

                        return $sResultFileName;
                        
                    }
                }
            }
        }
    }
}

$sImage = uploadImageFile();
echo '<div align=center><img src="'.$sImage.'" /></div>';
echo $sImage;
?>
      <!-- add styles -->
        <link href="css/main.css" rel="stylesheet" type="text/css" />
        <link href="css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />

        <!-- add scripts -->
        <script src="js/jquery.min.js"></script>
        <script src="js/jquery.Jcrop.min.js"></script>
        <script src="js/script.js"></script>
    </head>
    <body>

        <div class="demo">
            <div class="bbody">

                <!-- upload form -->
                <form id="upload_form" enctype="multipart/form-data" method="post" onsubmit="return checkForm()">
                    <!-- hidden crop params -->
                    <input type="hidden" id="x1" name="x1" />
                    <input type="hidden" id="y1" name="y1" />
                    <input type="hidden" id="x2" name="x2" />
                    <input type="hidden" id="y2" name="y2" />

                    <h2>Step1: Please select image file</h2>
                    <div><input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" /></div>

                    <div class="error"></div>

                    <div class="step2">
                        <h2>Step2: Please select a crop region</h2>
                        <img id="preview"/> <!-- QUESTA È LA PREVIEW -->

                        <div class="info">
                            <label>File size</label> <input type="text" id="filesize" name="filesize" />
                            <label>Type</label> <input type="text" id="filetype" name="filetype" />
                            <label>Image dimension</label> <input type="text" id="filedim" name="filedim" />
                            <label>W</label> <input type="text" id="w" name="w" />
                            <label>H</label> <input type="text" id="h" name="h" />
                        </div>

                        <input type="submit" value="Upload" />
                    </div>
                </form>
            </div>
        </div>
    </body>
</html>

script.js
Codice:
function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

// check for selected crop region
function checkForm() {
    if (parseInt($('#w').val())) return true;
    $('.error').html('Please select a crop region and then press Upload').show();
    return false;
};

// update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
    $('#x1').val(e.x);
    $('#y1').val(e.y);
    $('#x2').val(e.x2);
    $('#y2').val(e.y2);
    $('#w').val(e.w);
    $('#h').val(e.h);
};

// clear info by cropping (onRelease event handler)
function clearInfo() {
    $('.info #w').val('');
    $('.info #h').val('');
};

function fileSelectHandler() {

    // get selected file
    var oFile = $('#image_file')[0].files[0];

    // hide all errors
    $('.error').hide();

    // check for image type (jpg and png are allowed)
    var rFilter = /^(image\/jpeg|image\/png)$/i;
    if (! rFilter.test(oFile.type)) {
        $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
        return;
    }

    // check for file size
    if (oFile.size > 55555250 * 1024) {
        $('.error').html('You have selected too big file, please select a one smaller image file').show();
        return;
    }

    // preview element
    var oImage = document.getElementById('preview');

    // prepare HTML5 FileReader
    var oReader = new FileReader();
        oReader.onload = function(e) {

        // e.target.result contains the DataURL which we can use as a source of the image
        oImage.src = e.target.result;
        oImage.onload = function () { // onload event handler

            // display step 2
            $('.step2').fadeIn(500);

            // display some basic image info
            var sResultFileSize = bytesToSize(oFile.size);
            $('#filesize').val(sResultFileSize);
            $('#filetype').val(oFile.type);
            $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);

            // Create variables (in this scope) to hold the Jcrop API and image size
            var jcrop_api, boundx, boundy;

            // destroy Jcrop if it is existed
            if (typeof jcrop_api != 'undefined') 
                jcrop_api.destroy();

            // initialize Jcrop
            $('#preview').Jcrop({
                minSize: [32, 32], // min crop size
                aspectRatio : 1, // keep aspect ratio 1:1
                bgFade: true, // use fade effect
                bgOpacity: .3, // fade opacity
                onChange: updateInfo,
                onSelect: updateInfo,
                onRelease: clearInfo
            }, function(){

                // use the Jcrop API to get the real image size
                var bounds = this.getBounds();
                boundx = bounds[0];
                boundy = bounds[1];

                // Store the Jcrop API in the jcrop_api variable
                jcrop_api = this;
            });
        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}

Aggiungo che ho già provato modificando width ed height di <img id="preview"/> ma diventerebbe statica quindi non va bene per le immagini più piccolo o quadrate
 
Ultima modifica:

frenkytribe

Utente Attivo
17 Gen 2013
87
0
0
Scusate per il doppio post ma non posso più modificare quello di prima, questo è il css relativo al jcrop, e come ultimo parametro c'è qualcosa che potrebbe essere inerente.
Codice:
/* jquery.Jcrop.min.css v0.9.10 (build:20120429) */
.jcrop-holder{direction:ltr;text-align:left;}
.jcrop-vline,.jcrop-hline{background:#FFF url(Jcrop.gif) top left repeat;font-size:0;position:absolute;}
.jcrop-vline{height:100%;width:1px!important;}
.jcrop-hline{height:1px!important;width:100%;}
.jcrop-vline.right{right:0;}
.jcrop-hline.bottom{bottom:0;}
.jcrop-handle{background-color:#333;border:1px #eee solid;font-size:1px;}
.jcrop-tracker{-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none;-webkit-user-select:none;height:100%;width:100%;}
.jcrop-handle.ord-n{left:50%;margin-left:-4px;margin-top:-4px;top:0;}
.jcrop-handle.ord-s{bottom:0;left:50%;margin-bottom:-4px;margin-left:-4px;}
.jcrop-handle.ord-e{margin-right:-4px;margin-top:-4px;right:0;top:50%;}
.jcrop-handle.ord-w{left:0;margin-left:-4px;margin-top:-4px;top:50%;}
.jcrop-handle.ord-nw{left:0;margin-left:-4px;margin-top:-4px;top:0;}
.jcrop-handle.ord-ne{margin-right:-4px;margin-top:-4px;right:0;top:0;}
.jcrop-handle.ord-se{bottom:0;margin-bottom:-4px;margin-right:-4px;right:0;}
.jcrop-handle.ord-sw{bottom:0;left:0;margin-bottom:-4px;margin-left:-4px;}
.jcrop-dragbar.ord-n,.jcrop-dragbar.ord-s{height:7px;width:100%;}
.jcrop-dragbar.ord-e,.jcrop-dragbar.ord-w{height:100%;width:7px;}
.jcrop-dragbar.ord-n{margin-top:-4px;}
.jcrop-dragbar.ord-s{bottom:0;margin-bottom:-4px;}
.jcrop-dragbar.ord-e{margin-right:-4px;right:0;}
.jcrop-dragbar.ord-w{margin-left:-4px;}
.jcrop-light .jcrop-vline,.jcrop-light .jcrop-hline{background:#FFF;filter:Alpha(opacity=70)!important;opacity:.70!important;}
.jcrop-light .jcrop-handle{-moz-border-radius:3px;-webkit-border-radius:3px;background-color:#000;border-color:#FFF;border-radius:3px;}
.jcrop-dark .jcrop-vline,.jcrop-dark .jcrop-hline{background:#000;filter:Alpha(opacity=70)!important;opacity:.7!important;}
.jcrop-dark .jcrop-handle{-moz-border-radius:3px;-webkit-border-radius:3px;background-color:#FFF;border-color:#000;border-radius:3px;}
.jcrop-holder img,img.jcrop-preview{max-width:none;}
Ho modificato
Codice:
.jcrop-holder img,img.jcrop-preview{max-width:none;}
in
Codice:
.jcrop-holder img,img.jcrop-preview{max-width:800px; max-height: 600px;}
e stavolta l' immagine viene delle dimensioni volute, tranne uno sfondo nero che rimane delle dimensioni naturali.... Ed il ritaglio non viene preciso.
 
Ultima modifica:
Discussioni simili
Autore Titolo Forum Risposte Data
F resize di un'immagine dopo l'upload. PHP 0
P asp upload image con resize peso senza componenti? Classic ASP 0
B upload con resize in php PHP 5
JellyBelly Upload Img+Resize Ajax 1
F galleria immagini upload e resize... PHP 4
D resize e upload qualcosa non va PHP 4
M Upload immagine con javascript problemi con FormData() Javascript 1
Z Upload protetto e sicuro PHP 1
L Modifica file upload in ASP Classic ASP 2
Cosina Creare bottone delete in form upload PHP 5
Cosina Creare bottone delete in form upload PHP 1
Cosina Upload multiplo con invio allegati per email PHP 0
Cosina Upload multiplo con archiviazione in cartella PHP 16
P Script upload immagini jQuery 0
L upload image tramite url e cache PHP 10
W Non fa l'upload PHP 0
L Upload di un'immagine all'interno di un database usando php PHP 6
S Upload file senza doverlo selezionare PHP 2
P Upload foto cover e profilo jQuery 0
G Upload file error Apache 0
R Modifica codice per l'upload di più file PHP 1
S Problemi con modulo upload video php (help!) PHP 0
S [PHP] Upload stesso file PHP 14
max1974 [Javascript] dropzone upload to server Javascript 0
S [ASP.Net] [ASP] Upload Image ASP.NET 6
F [PHP] Informazioni upload PHP 11
G [PHP] upload file in server: percorso cartella PHP 2
M Upload 4 file php PHP 11
M [ASP] Upload file da form controllo Classic ASP 5
D [PHP] Upload intera cartella PHP 2
felino [PHP] Uploadify: upload immagini PHP 0
M [PHP] Nome file, upload e rinominare PHP 2
R Configurazione upload ftp su dvr IP Cam e Videosorveglianza 3
M [PHP] upload di un file esistente overwrite PHP 1
N [PHP] Test per l'upload di file attraverso un bot Telegram PHP 2
L [PHP] problema con upload e javascript (upload multiplo) Javascript 2
L [PHP] upload con errore PHP 2
V [PHP] Upload Excel in db PHP 0
jailbait [PHP] Upload immagine e stampa a schermo PHP 0
G PHP upload dati ed immagine PHP 7
F [PHP] Validare form prenotazione appuntamento tattoo con upload image PHP 0
D [PHP] Upload encrypt image PHP 0
C [PHP] Problema upload file (multiplo) PHP 1
P [PHP] Upload multiplo PHP 4
N [PHP] Problema upload immagini wordpress PHP 2
S [PHP] Upload file... PHP 6
michelangelopaone IPCAM Szinocam e upload FTP IP Cam e Videosorveglianza 0
razzor1994 Remote Upload Server Dedicati e VPS 0
P Barra upload file jQuery 1
giancadeejay [PHP] Aggiornare DB tramite UPLOAD file .csv PHP 39

Discussioni simili