2013-05-28 1 views
-2

Пожалуйста, проверьте код ниже, я использую jquery с PHP-кодом. У меня нет такого большого количества знаний о PHP, поэтому, пожалуйста, вытащите меня отсюда. Мне нужны страницы PHP и html-страница разделяться. Вот мой popup.html. Где я сделал неверный код, пожалуйста, сообщите мнеОшибка при обрезании изображения, сохранить изображение

<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Popup</title> 
<link rel="stylesheet" href="css/imgareaselect-animated.css" type="text/css" /> 
<link rel="stylesheet" href="css/imgareaselect-default.css" type="text/css" /> 
<link rel="stylesheet" href="css/imgareaselect-deprecated.css" type="text/css" /> 
<script src="jquery.min.js" type="text/javascript"></script> 
<script src="jquery.imgareaselect.pack.js"></script> 
<script src="jquery.imgareaselect.min.js"></script> 
<script src="jquery.imgareaselect.js"></script> 
</head> 
<body> 
<form id="cropimage" method="post" enctype="multipart/form-data"> 
    <input type="file" value="" size="" class="Textbox FieldRequired" name="ProductFields[3]" id="files"> 
    <input type="submit" value="upload" class="uploadphoto"/> 
    <div id="popup_box"> 
    <!-- OUR PopupBox DIV--> 
    <a id="popupBoxClose">close</a> 
    <div id="popup_box1" style="margin:0 auto; width:600px"> 
    <div id="thumbs" style="padding:5px; width:600px"></div> 
    <div style="width:600px"> 
    <input type="hidden" name="image_name" id="image_name" value="" /> 
    <input type="submit" name="submit" value="Submit" /> 
</form> 
</div> 
</div> 
</div> 
<div id="container"> <!-- Main Page --> 
</div> 
<script type="text/javascript"> 
$(document).ready(function() { 
$(".uploadphoto").click(function() { 
    if(document.getElementById('files').files.length == 0){ 
     alert('Select an Image first'); 
     return false;} 
    // }else { 
     // When upload button is pressed, load the Popupbox First 
     loadPopupBox(); 
      // } 
     $('#popupBoxClose').click(function() {   
      unloadPopupBox(); 
      $('.imgareaselect-outer').css('display','none'); 
      $('.imgareaselect-selection').css('display','none'); 
      $('.imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-handle').css('display','none'); 
      document.getElementById('files').value=""; 
     }); 

     $('#container').click(function() { 
      unloadPopupBox(); 
     }); 

     function unloadPopupBox() { // TO Unload the Popupbox 
      $('#popup_box').fadeOut("slow"); 
      $("#container").css({ // this is just for style  
       "opacity": "1" 
      }); 
     } 
     function loadPopupBox() { // To Load the Popupbox 
      $('#popup_box').fadeIn("slow"); 
      $("#container").css({ // this is just for style 
       "opacity": "1.5" 
      });   
     } 
    }); 

}); 
</script> 
<script type="text/javascript"> 
$(document).ready(function() {  
//$('.FieldRequired').attr('id','files'); 
// set up variables 
var reader = new FileReader(), 
    i=0, 
    numFiles = 0, 
    imageFiles; 

// use the FileReader to read image i 
function readFile() { 
    reader.readAsDataURL(imageFiles[i]) 
} 
// define function to be run when the File 
// reader has finished reading the file 
reader.onloadend = function(e) { 

    // make an image and append it to the div 
    var image = $('<img>').attr('src', e.target.result); 
    var imgdiv = $('#popup_box'); 
    $(imgdiv).append(image); 
    $('#popup_box img').attr('id','img1'); 

function getSizes(im,obj) 
    { 
     var x_axis = obj.x1; 
     var x2_axis = obj.x2; 
     var y_axis = obj.y1; 
     var y2_axis = obj.y2; 
     var thumb_width = obj.width; 
     var thumb_height = obj.height; 
     if(thumb_width > 0) 
      { 
       if(confirm("Do you want to save image..!")) 
        { 
         $.ajax({ 
          type:"GET", 
          url:"ajax_image.php?t=ajax&img="+$("#image_name").val()+"&w="+thumb_width+"&h="+thumb_height+"&x1="+x_axis+"&y1="+y_axis, 
          cache:false, 
          success:function(rsponse) 
           { 
           $("#cropimage").hide(); 
            $("#thumbs").html(""); 
            $("#thumbs").html("<img src='uploads/"+rsponse+"' />"); 
           } 
         }); 
        } 
      } 
     else 
      alert("Please select portion..!"); 
    } 

$(document).ready(function() { 
    $('img#img1').imgAreaSelect({ 
     aspectRatio: '1:1', 
     onSelectEnd: getSizes 
    }); 
}); 

// if there are more files run the file reader again 
    if (i < numFiles) { 
     i++; 
     readFile(); 
    } 
}; 
$(".uploadphoto").click(function() { 

    imageFiles = document.getElementById('files').files 
    // get the number of files 
    numFiles = imageFiles.length; 
    readFile();   

}); 


}); 
$('#popup_box1').load('save_image.php'); 
</script> 
<style type="text/css"> 
/* popup_box DIV-Styles*/ 
#popup_box { 
    display:none; /* Hide the DIV */ 
    position:fixed; 
    _position:absolute; /* hack for internet explorer 6 */ 
    height:500px; 
    width:500px; 
    background:#FFFFFF; 
    left: 30%; 
    top: 20%; 
    z-index:100; /* Layering (on-top of others), if you have lots of layers: I just maximized, you can change it yourself */ 
    margin-left: 15px; 
    /* additional features, can be omitted */ 
    border:2px solid #ff0000; 
    padding:15px; 
    font-size:15px; 
    -moz-box-shadow: 0 0 5px #ff0000; 
    -webkit-box-shadow: 0 0 5px #ff0000; 
    box-shadow: 0 0 5px #ff0000; 
} 
#popup_box img { 
height: 476px; 
    margin: 3px; 
    width: 494px; 
} 
#container { 
    background: #d2d2d2; /*Sample*/ 
    width:100%; 
    height:100%; 
} 
a { 
    cursor: pointer; 
    text-decoration:none; 
} 
/* This is for the positioning of the Close Link */ 
#popupBoxClose { 
    background: url("close.png") no-repeat scroll 0 0 transparent; 
    color: transparent; 
    font-size: 20px; 
    line-height: 26px; 
    position: absolute; 
    right: -28px; 
    top: -14px; 
} 
</style> 
</body> 

Вот мой Сохранить image.php

<?php 
//include('db.php'); 
session_start(); 
$session_id='1'; //$session id 

$path = "uploads/"; 
?> 
<?php 

    $valid_formats = array("jpg", "png", "gif", "bmp"); 
    if(isset($_REQUEST['submit'])) 
     { 
      $name = $_FILES['files']['name']; 
      $size = $_FILES['files']['size']; 

      if(strlen($name)) 
       { 
        list($txt, $ext) = explode(".", $name); 
        if(in_array($ext,$valid_formats) && $size<(1024*1024)) 
         { 
          $actual_image_name = time().substr($txt, 5).".".$ext; 
          $tmp = $_FILES['files']['tmp_name']; 
          if(move_uploaded_file($tmp, $path.$actual_image_name)) 
           { 
           //mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'"); 
            $image="<h1>Please drag on the image</h1><img src='uploads/".$actual_image_name."' id=\"photo\" style='max-width:500px' >"; 

           } 
          else 
           echo "failed"; 
         } 
        else 
         echo "Invalid file formats..!";     
       } 
      else 
       echo "Please select image..!"; 
     } 
?> 

<div style="margin:0 auto; width:600px"> 
<?php if(isset($image))echo $image; ?> 
<div id="thumbs" style="padding:5px; width:600px"></div> 
<div style="width:600px"> 

Получение ошибки "NetworkError: 404 Не найдено - http://abc.com/CropImage-PHP/uploads/%3Cbr%20/%3E%3Cb%3EWarning%3C/b%3E:%20%20imagecreatefromjpeg(uploads/undefined)%20%5B%3Ca%20href="

Получение ошибки во время создание папки для загрузки.

+1

Урм, что именно ваш вопрос здесь! –

+0

эй ваш данный html-код неуместен и полон ошибок, пожалуйста, дайте отредактированную версию вопроса. И как сказал харша, где ваш вопрос здесь? –

+0

@ A.F.M.NazmusSakib Я отредактировал мой код, пожалуйста, проверьте его.Я хочу сохранить обрезанное изображение в папку uploads – Rash

ответ

2

PHP имеет Bult в GD Librery

Я не, знаю, если это необходимо, что для и создать функцию JS для обрезки изображения. Для управления изображениями доступно множество функций. Поэтому нет необходимости выполнять дополнительную работу.

Вы также можете проверить эту ссылку здесь https://gist.github.com/philBrown/880506

Проверьте свои функции. Вы можете легко выполнить свою работу с помощью класса манипуляции с изображениями. Использование образцов этого класса ...

$myImage = new ImageManipulator($_FILES['form_field_name']['tmp_name']); 

Затем вы можете изменить размер изображения с помощью этой одной строке кода ...

$myImage->resample(480, 320); // resize to 480x320 

так же вы можете обрезать его, увеличить его .. для обрезки ... (заданное значение для переменных)

$myImage->crop($x1_axis, $y1_axis, $x2_axis, $y2_axis); 

для сохранения в пункт назначения ....

$myImage->save('/path/to/uploadfolder/image.jpg', IMAGETYPE_JPEG); 

Я думаю, вам будет легко справиться с манипуляциями с изображением этого класса. Я не знаю, насколько это полезно для вас, но это хороший класс для манипуляций с изображениями.

И ваш Html все еще имеет несоответствующие окончания тегов.

должно быть ...

<form id="cropimage" method="post" enctype="multipart/form-data"> 
    <input type="file" value="" size="" class="Textbox FieldRequired" name="ProductFields[3]" id="files"> 
    <input type="submit" value="upload" class="uploadphoto"/> 
    <div id="popup_box"> 
    <!-- OUR PopupBox DIV--> 
    <a id="popupBoxClose">close</a> 
    <div id="popup_box1" style="margin:0 auto; width:600px"> 
    <div id="thumbs" style="padding:5px; width:600px"></div> 
    <div style="width:600px"> 
    <input type="hidden" name="image_name" id="image_name" value="" /> 
    <input type="submit" name="submit" value="Submit" /> 
</div> 
</div> 
</div> 
</form> 

вместо текущего кода ...

<form id="cropimage" method="post" enctype="multipart/form-data"> 
    <input type="file" value="" size="" class="Textbox FieldRequired" name="ProductFields[3]" id="files"> 
    <input type="submit" value="upload" class="uploadphoto"/> 
    <div id="popup_box"> 
    <!-- OUR PopupBox DIV--> 
    <a id="popupBoxClose">close</a> 
    <div id="popup_box1" style="margin:0 auto; width:600px"> 
    <div id="thumbs" style="padding:5px; width:600px"></div> 
    <div style="width:600px"> 
    <input type="hidden" name="image_name" id="image_name" value="" /> 
    <input type="submit" name="submit" value="Submit" /> 
</form> 
</div> 
</div> 
</div> 

дивы вы начали в тегах лучше, чтобы закончить его в этом теге.

Спасибо.

+0

Можно ли использовать эту функцию для обрезки изображения при редактировании экрана? –

2

Если вы хотите создать новое изображение в указанных вами размерах, поддерживая соотношение сторон и вытягивая изображение при необходимости. Затем этот код для вас :)

function resize_image_crop($image, $width, $height) 
{ 

    $w = @imagesx($image); //current width 

    $h = @imagesy($image); //current height 
    if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; } 
    if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed 
    $ratio = $width/$w;  //try max width first... 
    $new_w = $width; 
    $new_h = $h * $ratio;  
    if ($new_h < $height) { //if that created an image smaller than what we wanted, try the other way 
     $ratio = $height/$h; 
     $new_h = $height; 
     $new_w = $w * $ratio; 
    } 
    $image2 = imagecreatetruecolor ($new_w, $new_h); 
    imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);  
    if (($new_h != $height) || ($new_w != $width)) { //check to see if cropping needs to happen 
     $image3 = imagecreatetruecolor ($width, $height); 
     if ($new_h > $height) { //crop vertically 
      $extra = $new_h - $height; 
      $x = 0; //source x 
      $y = round($extra/2); //source y 
      imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height); 
     } else { 
      $extra = $new_w - $width; 
      $x = round($extra/2); //source x 
      $y = 0; //source y 
      imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height); 
     } 
     imagedestroy($image2); 
     return $image3; 
    } else { 
     return $image2; 
    } 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^