Ir para conteúdo
Fórum Script Brasil
  • 0

AjaxCrop


Gustavo Ribas Logullo

Pergunta

Eae pessoal tudo beleza?

Sou novo aqui no fórum e este é meu primeiro post e junto com ele já trago um problema que há tempos está me encomodando e acho que vocês poderão me ajudar a resolvê-lo.

É o seguinte:

Eu estou utilizando o seguinte script: AjaxCrop

Até aí tudo ok, porém, o problema está na hora de fazer o script de alterar. Para inserir a imagem e utilizar o script tudo certo. O problema real acontece na hora em que eu quero alterar uma imagem já cadastrada pelo script no sistema. Eu até consegui fazer ele listar as imagens tal, mas não consigo selecionar alguma área da imagem. Abaixo mando os scripts que estou utilizando para vocês darem uma analisada e tentarmos juntos resolver este problemão.

// Script func.php
function resizeImgAltera($Array)
{
  $NomeArquivo = date('YmdHis');

  $UploadDir = $Array['uploaddir'];
  $TempDir = $Array['tempdir'];

  if(isset($_GET['id_editar']) and $_GET['id_editar'] != '' and isset($_GET['album_fotos']) and $_GET['album_fotos'] != '')
  {
    $id_editar = $_GET['id_editar'];
    $album_fotos = $_GET['album_fotos'];

    // Le os respectivos dados para alterar
    $QueryAltera = mysql_query
    (
      'SELECT *
       FROM fotos
       WHERE id_album_fotos = ' . $album_fotos . '
       AND id = ' . $id_editar . ''
    );
    $ArrayAltera = mysql_fetch_array($QueryAltera);
    $Foto = $ArrayAltera['foto'];
    $CaminhoFoto = '../../../upload/album_fotos/miniaturas/' . $Foto . '';

    $TamanhoFoto = getimagesize('../../../upload/album_fotos/miniaturas/' . $Foto . '');
    $Largura = $TamanhoFoto[0];
    $Altura = $TamanhoFoto[1];
    echo $TamanhoFoto;
  }

  $TempName = md5($Foto);

  //echo $TempName;

  $ImagemParte  = pathinfo($Foto);
  $NovoNome     = strtolower($NomeArquivo.'.'.$ImagemParte['extension']);
  $Ext = strtolower($ImagemParte['extension']);

  $ExtPermissao = array('gif','jpg','jpeg','png');

  if(!in_array($Ext, $ExtPermissao))
  {
    echo '<p class="uperror">Esta imagem tem extensão diferente de: JPG, GIF ou PNG.</p>';
    exit;
  }

  $ArquivoTempUpload = $TempDir . $NovoNome;
  $NovoArquivoUpload = $UploadDir . $NovoNome;

  // Arquivo menor que 1.3MB
  if(filesize($CaminhoFoto) < 2097000)
  {
    if(move_uploaded_file($TempName, $ArquivoTempUpload))
    {
      $Array['ArquivoTempUpload'] = $ArquivoTempUpload;
      $Array['NovoArquivoUpload'] = $NovoArquivoUpload;

      asidoImg($Array);

      unlink($ArquivoTempUpload);
      exit;
    }
  }
  else
  {
    echo '<p class="uperror">A imagem precisa ter tamanho inferior a 1.3MB</p>';
    exit;
  }
}

function resizeImg($Array)
{
  $NomeArquivo = date('YmdHis');

  $UploadDir = $Array['uploaddir'];
  $TempDir = $Array['tempdir'];

  $TempName = $_FILES['imagem']['tmp_name'];

  //echo $TempName;

  $ImagemParte  = pathinfo($_FILES['imagem']['name']);
  $NovoNome     = strtolower($NomeArquivo.'.'.$ImagemParte['extension']);

  $Ext = strtolower($ImagemParte['extension']);

  $ExtPermissao = array('gif','jpg','jpeg','png');

  if(!in_array($Ext, $ExtPermissao))
  {
    echo '<p class="uperror">Esta imagem tem extensão diferente de: JPG, GIF ou PNG.</p>';
    exit;
  }

  $ArquivoTempUpload = $TempDir . $NovoNome;
  $NovoArquivoUpload = $UploadDir . $NovoNome;
        
  // Arquivo menor que 1.3MB
  if($_FILES['imagem']['size'] < 2097000)
  {
    if(move_uploaded_file($TempName, $ArquivoTempUpload))
    {
      $Array['ArquivoTempUpload'] = $ArquivoTempUpload;
      $Array['NovoArquivoUpload'] = $NovoArquivoUpload;

      asidoImg($Array);

      unlink($ArquivoTempUpload);
      exit;
    }
  }
  else
  {
    echo '<p class="uperror">A imagem precisa ter tamanho inferior a 1.3MB</p>';
    exit;
  }
}

function resizeThumb($Array)
{
  $NomeArquivo = date('YmdHis');
  $Array['ArquivoTempUpload'] = $Array['img_src'];
  $Array['NovoArquivoUpload'] = $Array['uploaddir'] . strtolower($NomeArquivo) . '.jpg';

  asidoImg($Array);
  exit;
}

function asidoImg($Array)
{
  include('asido/class.asido.php');
  asido::driver('gd');

  $height = $Array['height'];
  $width = $Array['width'];
  $x = $Array['x'];
  $y = $Array['y'];

  $Processo = asido::image($Array['ArquivoTempUpload'], $Array['NovoArquivoUpload']);

  if($Array['thumb'] === true)
  {
    Asido::Crop($Processo, $x, $y, $width, $height);
  }
  else
  {
    Asido::Frame($Processo, $width, $height, Asido::Color(255, 255, 255));
  }

  // always convert to jpg
  Asido::convert($Processo, 'image/jpg');

  $Processo->Save(ASIDO_OVERWRITE_ENABLED);

  $NomeArquivo = array('imagem'=> $Array['NovoArquivoUpload']);

  // echo $user_id;
  // delete old file

  echo $NomeArquivo['imagem'];
}
// Script: upload.php
include('func.php');

  if($_GET['act'] == 'thumb')
  {
    $Array = array
    (
      'uploaddir'       => '../../../upload/album_fotos/miniaturas/',
      'tempdir'         => '../../../upload/album_fotos/temp/',
      'height'          => $_POST['height'],
      'width'                   => $_POST['width'],
      'x'         => $_POST['x'],
      'y'         => $_POST['y'],
      'img_src'         => $_POST['img_src'],
      'thumb'                   => true
    );
    resizeThumb($Array);
    exit;
  }
  elseif($_GET['act'] == 'upload')
  {
    $big_arr = array
    (
      'uploaddir'       => '../../../upload/album_fotos/grandes/',
      'tempdir'   => '../../../upload/album_fotos/temp/',
      'height'    => $_POST['height'],
      'width'     => $_POST['width'],
      'x'         => 0,
      'y'         => 0
    );
    resizeImg($big_arr);
  }
  else
  {
    //
  }
// Script: custom.js
$(function()
{
  $("#show_details").click(function()
  {
    $("#about_details").slideToggle("slow");
  });

  function preview(img, selection)
  {
    if(!selection.width || !selection.height) return;

    //200 is the #preview dimension, change this to your liking
    var scaleX = 200 / selection.width; 
    var scaleY = 200 / selection.height;

    $('#preview img').css
    ({
      width: Math.round(scaleX * $('#big').attr('width')),
      height: Math.round(scaleY * $('#big').attr('height')),
      marginLeft: -Math.round(scaleX * selection.x1),
      marginTop: -Math.round(scaleY * selection.y1)
    });

    $('.x1').val(selection.x1);
    $('.y1').val(selection.y1);
    $('.x2').val(selection.x2);
    $('.y2').val(selection.y2);
    $('.width').val(selection.width);
    $('.height').val(selection.height);    
  }

  $("form").submit(function()
  {
    var fname = $(this).attr('name');

    //check if they have made a thumbnail selection
    if(fname == 'upload_thumb')
    {
      if($('#x1').val() == "" || $('#y1').val() == "" || $('#width').val() <= "0" || $('#height').val() <= "0")
      {
        alert("Voce precisa selecionar a area primeiro");
        return false;
      }
    }

    $('#big').imgAreaSelect({hide:true});
    $('#notice').text('Carregando...').fadeIn();

    $('#upload_target').unbind().load(function()
    {
      var img = $('#upload_target').contents().find('body ').html();

      if(fname == 'upload_big')
      {
        // load to preview image
        $('#preview').html(img);
        var img_id = 'big';

        /////// get image source , this will be passed into PHP
        $('.img_src').attr('value',img)
        $('#preview').html('<img src="../../../upload/album_fotos/miniaturas/'+img+'" />');
      }

      $('#div_'+fname).html('<img id="'+img_id+'" src="../../../upload/album_fotos/grandes/'+img+'" />');

      if($(img).attr('class') != 'uperror')
      {
        $('#upload_thumb').show();
        //area select plugin http://odyniec.net/projects/imgareaselect/examples.html
        $('#big').imgAreaSelect
        ({
          aspectRatio: '1:1',
          handles: true,
          fadeSpeed: 200,
          resizeable:false,
          maxHeight:300,
          maxWidth:200,
          minHeight:100,
          minWidth:50,
          onselectChange: preview
        });
      }
      else
      {
        //hide them
        $('#upload_thumb').hide();
      }

      $('#notice').fadeOut();

      // we have to remove the values
      $('.width , .height , .x1 , .y1 , #file').val('');

    });
  });
});
E por final o codigo da pagina que faz o upload do script
// Script: alt_foto.php
<?php
  // Verifica erros
  error_reporting(0);

  // Inicia sessao
  session_start();

  include "conectar.php";
  include "logado.php";

  $id_editar = isset($_GET["id_editar"]) ? $_GET["id_editar"] : FALSE;

  $album_fotos = isset($_GET["album_fotos"]) ? $_GET["album_fotos"] : FALSE;

  $status = isset($_POST["status"]) ? $_POST["status"] : FALSE;
  $foto = isset($_POST["foto"]) ? $_POST["foto"] : FALSE;

  $sql = "SELECT * FROM album_fotos WHERE id='$album_fotos'";
  $query = mysql_query($sql);
  $linha = mysql_fetch_array($query);
  $nome_album_fotos = $linha["titulo"];

  if($foto && $status){
                $sql = "UPDATE fotos SET foto='$foto', status='$status' WHERE id='$id_editar'";
                $query = mysql_query($sql);
                $resultado = "Dados alterados com sucesso.";
                header("Location: fotos.php?resultado=$resultado&id_album_fotos=$album_fotos");
  }

  include "inc_header.php";

  // Le os respectivos dados para alterar
  $QueryAltera = mysql_query
  (
    'SELECT *
     FROM fotos
     WHERE id_album_fotos = ' . $album_fotos . '
     AND id = ' . $id_editar . ''
  );
  $ArrayAltera = mysql_fetch_array($QueryAltera);
  $Foto = $ArrayAltera['foto'];

  include 'ajax/crop/upload_alt.php';
?>

<link rel="stylesheet" type="text/css" href="ajax/crop/css/imgareaselect-default.css" />
<link rel="stylesheet" type="text/css" href="ajax/crop/css/styles.css" />

&lt;script type="text/javascript" src="ajax/crop/js/jquery.min.js"></script>
&lt;script type="text/javascript" src="ajax/crop/js/jquery.imgareaselect.min.js"></script>
&lt;script type="text/javascript" src="ajax/crop/js/custom.js"></script>

<body>

  <div id="div_center">

    <div id="wrap">

      <div id="geral">

        <?php
          include "inc_topo.php";
        ?>

        <div id="miolo">
          <p class="inicio">
            « 
            <a href="index.php">Início</a>
          </p>

          <h3>Clientes > <?php echo $nome_album_fotos; ?> > Adicionar Foto</h3>

          <div id="uploader">

            <div id="big_uploader">
              <form name="upload_big" id="upload_big" method="post" enctype="multipart/form-data"
                    action="ajax/crop/upload.php?act=upload" target="upload_target">

                <label for="imagem">1.Selecione uma imagem:</label>
                <input name="imagem" id="file" size="27" type="file" />
                <br />
                <br />
                <label for="altura">Altura:</label>
                <input type="text" name="height" value="450" size="5"/>
                <br />
                <br />
                <label for="largura">Largura:</label>
                <input type="text" name="width" value="450" size="5" />
                <br />
                <br />
                <input type="submit" name="action" value="Upload" />

              </form>
            </div>

            <div id="notice">Enviando...</div>

            <div id="content">
              <img src="ajax/crop/images/top.jpg" width="798" height="38" alt="Topo" title="Topo" />

              <div id="uploaded">
                <h4>2. Imagem carregada - Clique e arraste para definir a dimensão da imagem</h4>

                <?php
                  /* if($Foto != '')
                  {
                    echo '<div id="div_upload_big">',
                           '<img id="big" src="../../../upload/album_fotos/grandes/' . $Foto . '" style="width: 450px;" />',
                         '</div>';
                  }
                  else
                  {
                    echo '<div id="div_upload_big"></div>';
                  } */
                ?>
                <div id="div_upload_big"></div>

                <form name="upload_thumb" id="upload_thumb" method="post" action="ajax/crop/upload.php?act=thumb"
                      target="upload_target">

                  <?php
                    /* if($Foto != '')
                    {
                      echo '<input type="hidden" name="img_src" id="img_src" class="img_src" value="../../../upload/album_fotos/grandes/' . $Foto . '" />';
                    }
                    else
                    {
                      echo '<input type="hidden" name="img_src" id="img_src" class="img_src" />';
                    } */
                  ?>
                  <input type="hidden" name="img_src" id="img_src" class="img_src" />
                  <input type="hidden" name="height" value="0" id="height" class="height" />
                  <input type="hidden" name="width" value="0" id="width" class="width" />

                  <input type="hidden" id="y1" class="y1" name="y" />
                  <input type="hidden" id="x1" class="x1" name="x" />
                  <input type="hidden" id="y2" class="y2" name="y1" />
                  <input type="hidden" id="x2" class="x2" name="x1" />
                  <input type="submit" value="create thumbnail" />

                </form>
              </div>

              <div id="thumbnail">
                <h4>Visualização</h4>

                <?php
                  /* if($Foto != '')
                  {
                    echo '<div id="preview">',
                           '<img src="../../../upload/album_fotos/grandes/' . $Foto . '" />',
                         '</div>';
                  }
                  else
                  {
                    echo '<div id="preview"></div>';
                  } */
                ?>
                <div id="preview"></div>

                <h4>Thumbnail</h4>
                <?php
                  /* if($Foto != '')
                  {
                    echo '<div id="div_upload_thumb">',
                           '<img src="../../../upload/album_fotos/miniaturas/' . $Foto . '" />',
                         '</div>';
                  }
                  else
                  {
                    echo '<div id="div_upload_thumb"></div>';
                  } */
                ?>
                <div id="div_upload_thumb"></div>

                <div id="details">

                  <table width="200">
                    <tr>
                      <td colspan="2">
                        Image Source
                        <br />
                        <input type="text" name="img_src" class="img_src" size="35" />
                      </td>
                    </tr>

                    <tr>
                      <td>
                        Height
                        <br />
                        <input type="text" name="height" class="height" size="5" />
                      </td>
                      <td>
                        Width
                        <br />
                        <input type="text" name="width" class="width" size="5" />
                      </td>
                    </tr>

                    <tr>
                      <td>
                        Y1
                        <br />
                        <input type="text" class="y1"  size="5"/>
                      </td>
                      <td>
                        X1
                        <br />
                        <input type="text" class="x1" size="5" />
                      </td>
                    </tr>

                    <tr>
                      <td>
                        Y2
                        <br />
                        <input type="text" class="y2" size="5" />
                      </td>
                      <td>
                        X2
                        <br />
                        <input type="text" class="x2" size="5" />
                      </td>
                    </tr>
                  </table>

                </div>

              </div><!-- thumbnail -->

              <img src="ajax/crop/images/btm.jpg" width="798" height="38" alt="Bottom" title="Bottom" />

            </div>

            <iframe id="upload_target" name="upload_target" src=""
                    style="width:100%; height: 400px; border: 1px solid #ccc; display:none;"></iframe>

          </div>



        </div><!-- miolo -->

        <?php
          include "inc_rodape.php";
        ?>

      </div>

    </div>

  </div>

</body>

</html>

Pessoal, vamos conversando sobre este problema.

Preciso resolver este problema o quanto antes, o cliente já está me torrando as paciências.

Atenciosamente,

Gustavo Ribas Logullo

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...