Array ? How to resolve

Asked

Viewed 83 times

0

There is this site that I am setting up where I made a junction of a code that insert watermark with a form where it would be possible to choose which brand would be superimposed on the image that was uploaded. As I’m still learning PHP, I had to do it by hand, option by option. How can I summarize all this code ? In addition, it is also possible that the script itself that inserts the . png under the photo insert over each other until you arrive at the final result when you have to create each option of . png with all watermarks option ?

To illustrate better, here’s the site I’m doing: http://ilhas.16mb.com

And this is the source code:

<script src="http://deepliquid.com/Jcrop/js/jquery.Jcrop.min.js"></script>
<script src="js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<link rel="stylesheet" href="demo_files/demos.css" type="text/css" />

<?php

        $S = isset($_POST['salvador']);
        $B = isset($_POST['brisas']);
        $P = isset($_POST['pontes']);
        $V = isset($_POST['porto_velho']);

        if($S && !$B && !$P && !$V) {
            $image_path = "avatares/salvador.png";
        } elseif ($B && !$S && !$P && !$V) {
            $image_path = "avatares/brisas.png";
        } elseif ($P && !$S && !$B && !$V) {
            $image_path = "avatares/pontes.png";
        } elseif ($V && !$S && !$B && !$P) {
            $image_path = "avatares/portovelho.png";
        } elseif ($S && $P && !$B && !$V) {
            $image_path = "avatares/salvador_pontes.png";
        } elseif ($S && $V && !$B && !$P) {
            $image_path = "avatares/salvador_portovelho.png";
        } elseif ($B && $V && !$S && !$P) {
            $image_path = "avatares/brisas_portovelho.png";
        } elseif ($B && $P && !$S && !$V) {
            $image_path = "avatares/brisas_pontes.png";
        } elseif ($S && $P && $V && !$B) {
            $image_path = "avatares/salvador_pontes_portovelho.png";
        } elseif ($B && $P && $V && !$S) {
            $image_path = "avatares/brisas_pontes_portovelho.png";
        } elseif ($S && $B && $P && $V) {
            $image_path = "avatares/todos.png";
        } elseif ($S && $B && !$P && !$V) {
            $image_path = "avatares/salvador_brisas.png";
        } elseif ($S && $B && $V && !$P) {
            $image_path = "avatares/todos_sem_pontes.png";
        } elseif ($S && $B && $P && !$V) {
            $image_path = "avatares/todos_sem_portovelho.png";
        } else {
            $image_path = "avatares/ilhas.png";
        }

function watermark_image($oldimage_name, $new_image_name){
    global $image_path;
    list($owidth,$oheight) = getimagesize($oldimage_name);
    $width = $height = 800;    
    $im = imagecreatetruecolor($width, $height);
    $img_src = imagecreatefromjpeg($oldimage_name);
    imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
    $watermark = imagecreatefrompng($image_path);
    list($w_width, $w_height) = getimagesize($image_path);        
    $pos_x = $width - $w_width; 
    $pos_y = $height - $w_height;
    imagecopy($im, $watermark, $pos_x, $pos_y, 0, 0, $w_width, $w_height);
    imagejpeg($im, $new_image_name, 100);
    imagedestroy($im);
    unlink($oldimage_name);
    return true;
}

$demo_image= "";
if(isset($_POST['createmark']) and $_POST['createmark'] == "Submit"){
    $path = "uploads/";
    $valid_formats = array("jpg","bmp","jpeg");
    $name = $_FILES['imgfile']['name'];
    if(strlen($name))
{
   list($txt, $ext) = explode(".", $name);
   if(in_array($ext,$valid_formats)&& $_FILES['imgfile']['size'] <= 10*256*1024)
    {
    $upload_status = move_uploaded_file($_FILES['imgfile']['tmp_name'], $path.$_FILES['imgfile']['name']);
    if($upload_status){
        $new_name = $path.time().".jpg";
        if(watermark_image($path.$_FILES['imgfile']['name'], $new_name))
                $demo_image = $new_name;

    }
    }
    else
    $msg = "A foto tem que ter menos que 2,5mb.";
    }
}

    # Conta quantos arquivos existem na pasta de upload
    $diretorio = scandir("uploads/");
    $qtd = count($diretorio) - 2;





?>


    <html lang="pt-br">

    <head>
        <meta charset="UTF-8">
        <title>Avatarizador</title>
        <link rel="stylesheet" href="avatar.css">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        <div id="conteudo">
            <form name="imageUpload" id="imageUpload" enctype="multipart/form-data" method="post" action="">
                <h1>Avatarizador !</h1>
                <div class="giro">V 2.0</div>
                <p class="texto">Já foram criadas <strong><?PHP echo ("$qtd"); ?></strong> fotos com o avatar do EREA Ilhas.</p>

                <input style="margin-bottom:15px;" type="file" name="imgfile" id="imgfile" />

                <p>Selo dos próximos encontros:</p>
                <!-- <p style="font-size:9pt;">Lembre que o EREA Salvador está concorrendo com o EREA Brisas, então escolhe apenas um deles ;)</p> -->
                <br>

                <input type="checkbox" name="salvador" value="on">
                <label class="texto">EREA Salvador 2017</label>

                <input type="checkbox" name="brisas" value="on">
                <label class="texto">EREA Brisas 2017</label>

                <input type="checkbox" name="pontes" value="on">
                <label class="texto">EREA Pontes 2016</label>

                <input type="checkbox" name="porto_velho" value="on">
                <label class="texto">EREA Porto Velho 2016</label>

                <br>

                <input type="submit" name="createmark" id="createmark" value="Submit" />

                <br>
                <?php
                    if(!empty($demo_image)){
                        echo '
                            <center>
                                <b>Click na imagem para fazer o download.</b>
                                <br><br>
                                <a href="'.$demo_image.'" download>
                                <img id="avatar" src="'.$demo_image.'" />
                                </a>
                            </center>
                            ';

                        # Salva dados em txt com o nome da foto para que possa ser rastreado quem criou o arquivo (avatar)
                        $arquivo = "rastro.txt"; /* Lembrar de mudar a permissão do .txt para 777 */
                        date_default_timezone_set('America/Bahia'); # Sao_Paulo para usar horário de Brasília (Não esqueça do horário de verão)
                        $data = date('d/m/Y H:i:s', time());
                        $ip = $_SERVER['REMOTE_ADDR'];    
                        $browser = $_SERVER['HTTP_USER_AGENT']; 
                        $fp = fopen($arquivo, "a+");   
                        fwrite($fp,"Arquivo: $new_name | Data: $data | IP: $ip | Navegador: $browser \n\r");   
                        fclose($fp);

                    }
                ?>
            </form>
        </div>
    </body>

    </html>
  • The problem is only this "selector"?

  • That Inkeliz, I don’t know how to do this in a nutshell. If I need to make any changes removing something or adding something, I have to redo everything one by one

  • I know an easy method, but I don’t know if it’s the best.

1 answer

2

By logic the names are with a pattern, so rename some getting like this:

Create a "separate" file and just change true and false to check how it would work, it’s easier.

<?php

$S = isset($_POST['salvador']);
$B = isset($_POST['brisas']);
$P = isset($_POST['pontes']);
$V = isset($_POST['porto_velho']);

if($S){$NomeAux[] = 'salvador';} // se tiver S tem salvador    
if($B){$NomeAux[] = 'brisas';} // se tiver B tem brisas    
if($P){$NomeAux[] = 'pontes';} // se tiver P tem pontes    
if($V){$NomeAux[] = 'portovelho';} // se tiver V tem portovelho   

$image_path = 'ilhas'; // para não bugar (:    

if(isset($NomeAux)){  // ****** Se tiver algum selecionado!    
    foreach($NomeAux as $nome){  // irá usar todos os nomes que possuem true    
        $image_path  .= $nome.'_';     
        // irá junta-los -> exemplo: salvador_ ou salvador_brisas_    
    }
}

// resulta nisto:    
$image_path = 'avatares/' . trim($image_path, '_') . '.png'; //***  Isto deve ser mantido, agora  está com o nome da variavel que utiliza!

// Remove a ultima _ adicioando e adicione o caminho.    
?>

IMPORTANT NOTE:

Change the todos_sem_portovelho.png for salvador_brisas_pontes.png

Change the todos_sem_pontes.png for salvador_brisas_portovelho.png

Change the todos.png for salvador_brisas_pontes_portovelho

Testing this.

  • When vc says to change true, it would be in input value (checkbox) ?

  • Exactly. Nothing changes. $S = isset($_POST['salvador']) (...) will have the value equivalent to TRUE and FALSE, only replace. I just chose to leave TRUE and FALSE so I can check easier. :)

  • Check the modification. isset() will set to "true" if it exists and "false" if it does not exist, so I directly put "true" and "false". Now it’s clearer what I meant.

  • I am experiencing these errors http://prntscr.com/9nt2xl

  • I think some things were missing. It’s easy to fix. Create an isset ($Nomeux) before the foreach and KEEP the "'avatares/'. Trim($image_path, '_'). '. png'" otherwise you will not find the file. I will edit it again by checking where it was changed.

  • I made a new change

  • I think now there is no problem. I will improve the formulation in the next answers. : S I am too lazy to stay due to several variables.

  • Dude, you are already helping immensely :D The mistakes are gone, but I couldn’t get the final image with the watermarks, I believe I’m missing in adapting something here, but I keep trying

  • Hint from those who also learned PHP in trial and error (no stroke, no nothing): give a var_dump($image_path) this will show what this variable is holding. See if it is the same as the one defined in the previous code (that manual).

  • Inkeliz, script working perfectly ! Just the question of the name of each . png that got boring kkkk, pq I will always have to create in the order that the person select, style: islans_salvador_breezes_bridges but if I do not select "breezes", I will have to create another . png with the name "ilhas_salvador_pontes" :)

  • This is the drawback. I don’t know how you’re using it (and which library/class). You may be able to do the following: add the image of islands + savior (saved! ) + breezes and save (you will have 3 together) and press. I used a similar system on a site and whenever I tried to 'go adding' without saving it did not work, as it was a test site I left for that very reason. For optimization it is not good to always do this with every request. It is ideal that once it already exists it uses it, then creates a variable (if this already exists use it, if not create it).

  • And is it possible to loop the water mark insertion code itself? So that it overlaps the . png ? So I only need to put the avatar of each city as Savior, Breezes, Bridges and Portovelho and the user himself could generate its final image with several possibilities

  • Yes, this is possible. But, there is this however. Save each 'merge' and click. Example: S + B = SB.png | SB.png + P = SBP.png (this contains the 3). Now, I don’t know how the images are or how it’s done. But I’ve done something similar this way.

  • yeah. That part I’m already lost in

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.