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

Sistema de crop image


LukinhasWeb

Pergunta

Galera sou novato aq e estou com um problema aq em script PHP, se trata de um sistema de crop image achei na net estou tentando adaptar em um sistema que tenho de gerenciamento de conteudo, so que a o está acontecendo é que a thumb que é gereda eu quero cadastrar no banco de dados mas não estou conseguindo fazer isso, já colequei um INSERT SQL mas está dando um pau ele cadastra mas a imagem não fica no banco tipo "299309

9344.jpg" fica somente os numeros e o nome fiquiticio que dado para a variavel  









<?php

    include('conexao.php');    


error_reporting (E_ALL ^ E_NOTICE);
session_start(); //Não remova este

//apenas atribuir um novo carimbo do tempo, se a variável de sessão está vazio
if (!isset($_SESSION['random_key']) || strlen($_SESSION['random_key'])==0){
    $_SESSION['random_key'] = strtotime(date('Y-m-d H:i:s')); //atribuir a hora para a variável de sessão
    $_SESSION['user_file_ext']= "";
}


#########################################################################################################
# CONSTANTS                                                                                                #
#Você pode alterar as opções abaixo                                                                        #
#########################################################################################################


$upload_dir = "fotos";                                                 // O diretório para as imagens a serem salvas em
$upload_path = $upload_dir."/";                                        // O caminho para onde a imagem será salva
$large_image_prefix = "resize_";                                     // O nome do prefixo a imagem grande
$thumb_image_prefix = "thumbnail_";                                    // O nome de prefixo para a imagem do polegar
$large_image_name = $large_image_prefix.$_SESSION['random_key'];    // Novo nome da imagem grande (anexar a hora para o arquivo)
$thumb_image_name = $thumb_image_prefix.$_SESSION['random_key'];    // Novo nome da imagem em miniatura (acrescentar a hora para o arquivo)
$max_file = "3";                                                     // O tamanho máximo do arquivo em MB
$max_width = "500";                                                    // Largura máxima permitida para a imagem grande
$thumb_width = "100";                                                // Largura da imagem em miniatura
$thumb_height = "100";                                                // Altura da imagem em miniatura


//Variaveis declaradas para serem inseridas no banco 
$data = "data";
$nome = "nome";
$des_cp = "des_cp";
$descricao = "descricao";


// Apenas um desses tipos de imagem deve ser permitido para upload
$allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
$allowed_image_ext = array_unique($allowed_image_types); // do not change this
$image_ext = "";    // initialise variable, do not change this.
foreach ($allowed_image_ext as $mime_type => $ext) {
    $image_ext.= strtoupper($ext)." ";
}


##########################################################################################################
# IMAGE FUNCTIONS                                                                                         #
# Você não precisa alterar essas funções                                                                 #
##########################################################################################################

function resizeImage($image,$width,$height,$scale) {
    list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    $imageType = image_type_to_mime_type($imageType);
    $newImageWidth = ceil($width * $scale);
    $newImageHeight = ceil($height * $scale);
    $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
    switch($imageType) {
        case "image/gif":
            $source=imagecreatefromgif($image); 
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            $source=imagecreatefromjpeg($image); 
            break;
        case "image/png":
        case "image/x-png":
            $source=imagecreatefrompng($image); 
            break;
      }
      
    imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
    
    switch($imageType) {
        case "image/gif":
              imagegif($newImage,$image); 
            break;
          case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
              imagejpeg($newImage,$image,90); 
            break;
        case "image/png":
        case "image/x-png":
            imagepng($newImage,$image);  
            break;
    }
    
    chmod($image, 0777);
    return $image;
}


//Você não precisa alterar essas funções
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
    list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    $imageType = image_type_to_mime_type($imageType);
    
    $newImageWidth = ceil($width * $scale);
    $newImageHeight = ceil($height * $scale);
    $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
    switch($imageType) {
        case "image/gif":
            $source=imagecreatefromgif($image); 
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            $source=imagecreatefromjpeg($image); 
            break;
        case "image/png":
        case "image/x-png":
            $source=imagecreatefrompng($image); 
            break;
      }
      
    imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
    switch($imageType) {
        case "image/gif":
              imagegif($newImage,$thumb_image_name); 
            break;
          case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
              imagejpeg($newImage,$thumb_image_name,90); 
            break;
        case "image/png":
        case "image/x-png":
            imagepng($newImage,$thumb_image_name);  
            break;
    }
    
    chmod($thumb_image_name, 0777);
    return $thumb_image_name;
}


//Você não precisa alterar essas funções
function getHeight($image) {
    $size = getimagesize($image);
    $height = $size[1];
    return $height;
}


//Você não precisa alterar essas funções
function getWidth($image) {
    $size = getimagesize($image);
    $width = $size[0];
    return $width;
}


//Image Locais
$large_image_location = $upload_path.$large_image_name.$_SESSION['user_file_ext'];
$thumb_image_location = $upload_path.$thumb_image_name.$_SESSION['user_file_ext'];



//Crie o diretório de upload com as permissões de direita, se ele não existir
if(!is_dir($upload_dir)){
    mkdir($upload_dir, 0777);
    chmod($upload_dir, 0777);
}


//Verifique se as imagens com o mesmo nome já existe
if (file_exists($large_image_location)){
    if(file_exists($thumb_image_location)){
        $thumb_photo_exists = "<img src=\"".$upload_path.$thumb_image_name.$_SESSION['user_file_ext']."\" alt=\"Thumbnail Image\"/>";
    }else{
        $thumb_photo_exists = "";
    }
       $large_photo_exists = "<img src=\"".$upload_path.$large_image_name.$_SESSION['user_file_ext']."\" alt=\"Large Image\"/>";
} else {
       $large_photo_exists = "";
    $thumb_photo_exists = "";
}

if (isset($_POST["upload"])) { 
    
    //Receba as informações do arquivo
    $userfile_name = $_FILES['image']['name'];
    $userfile_tmp = $_FILES['image']['tmp_name'];
    $userfile_size = $_FILES['image']['size'];
    $userfile_type = $_FILES['image']['type'];
    $filename = basename($_FILES['image']['name']);
    $file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
    
    //Somente o processo se o arquivo é um arquivo JPG, PNG ou GIF e abaixo do limite permitido
    if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
        
        foreach ($allowed_image_types as $mime_type => $ext) {
            
            //percorrer os tipos de imagem especificada e se coincide com a extensão, em seguida, sair
            //está tudo ok assim que vai verificar o tamanho do arquivo
            if($file_ext==$ext && $userfile_type==$mime_type){
                $error = "";
                break;
            }else{
                $error = "<font color='#cc0909'><strong>Somente Arquivos </strong></font><strong>".$image_ext."</strong><font color='#cc0909'><strong> s&atildeo Permitidos.</strong></font><br />";
            }
        }
        
        //verificar se o tamanho do arquivo é acima do limite permitido
        if ($userfile_size > ($max_file*1048576)) {
            $error.= "<font color='#cc0909'><strong>Tamanho M&aacute;ximo para o Envio de Imagem -  </strong></font><strong>".$max_file."MB"."</strong>";
        }
        
    }else{
        $error= "Selecione uma imagem para o Upload";
    }
    
    //Tudo está ok, então pode fazer o upload da imagem
    if (strlen($error)==0){
        
        if (isset($_FILES['image']['name'])){
            
            //Este arquivo pode agora tem uma extensão de arquivo desconhecido (esperamos que seja um dos acima estabelecidos!
            $large_image_location = $large_image_location.".".$file_ext;
            $thumb_image_location = $thumb_image_location.".".$file_ext;
            
            //colocar o arquivo ext na sessão assim que nós sabemos qual o ficheiro a procurar uma vez que seu upload
            $_SESSION['user_file_ext']=".".$file_ext;
            
            move_uploaded_file($userfile_tmp, $large_image_location);
            chmod($large_image_location, 0777);
            
            $width = getWidth($large_image_location);
            $height = getHeight($large_image_location);
            
            //Escala de imagem se for maior que a largura acima estabelecidos
            if ($width > $max_width){
                $scale = $max_width/$width;
                $uploaded = resizeImage($large_image_location,$width,$height,$scale);
            }else{
                $scale = 1;
                $uploaded = resizeImage($large_image_location,$width,$height,$scale);
            }
            
            //Excluir o arquivo miniatura para que o usuário pode criar um novo
            if (file_exists($thumb_image_location)) {
                unlink($thumb_image_location);
            }
        }
        
        //Atualize a página para mostrar a nova imagem carregado
        header("location:".$_SERVER["PHP_SELF"]);
        exit();
    }
}

if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
    
    //Receba as novas coordenadas para recortar a imagem.
    $x1 = $_POST["x1"];
    $y1 = $_POST["y1"];
    $x2 = $_POST["x2"];
    $y2 = $_POST["y2"];
    $w = $_POST["w"];
    $h = $_POST["h"];
    
    //Escala de imagem para o THUMB_WIDTH acima estabelecidos
    $scale = $thumb_width/$w;
    $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
    
    
        $sql = "INSERT INTO eventos (data, nome, des_cp, descricao, foto) VALUES('$data', '$nome', '$des_cp', '$descricao', '$thumb_image_name')";
                                                                                                                             // $thumb_image_name variavel com o nome da thumb
        $query = mysql_query($sql);
            
                
        if ($query == true) {
            echo "<div id='boxexcluir'>Registro Cadastrado com sucesso&nbsp;&nbsp;&nbsp;<img src='imagens/lixo_sim.png' border='0' /></div>";
            echo "<meta HTTP-EQUIV='refresh' CONTENT='3;URL=eventos.php'>";
        }
        else {
            echo "<div id='boxexcluirerro'>Não foi possível Cadastrar seu registro&nbsp;&nbsp;&nbsp;<img src='imagens/lixo_nao.png' border='0' /></div>";
            echo "<meta HTTP-EQUIV='refresh' CONTENT='3;URL=eventos.php'>";
        }        
    
    
    //Atualizar a página novamente para ver a miniatura
    header("location:".$_SERVER["PHP_SELF"]);
    exit();
}


if ($_GET['a']=="delete" && strlen($_GET['t'])>0){
    
//obter os locais de arquivo 
    $large_image_location = $upload_path.$large_image_prefix.$_GET['t'];
    $thumb_image_location = $upload_path.$thumb_image_prefix.$_GET['t'];
    if (file_exists($large_image_location)) {
        unlink($large_image_location);
    }
    if (file_exists($thumb_image_location)) {
        unlink($thumb_image_location);
    }
    header("location:".$_SERVER["PHP_SELF"]);
    exit(); 
}


?>

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,2k
    • Posts
      652k
×
×
  • Criar Novo...