2013-05-21 2 views
0

PHP를 사용하여 이미지 위에 텍스트를 쓰고 있습니다. 현재 이미지에서 새 이미지를 쉽게 작성하고 PHP를 사용하여 텍스트를 쓰고 있습니다.하지만 변경 사항 적용을 클릭하면이 새 이미지를 내 디렉토리 (move_uploaded_file)로 옮길 수도 있습니다. 현재 이미지를 새 이미지로 바꾸고 새 이미지 이름은 PHP를 사용하여 다운로드하기 때문에 이전 이미지와 동일해야합니다.@imagecreatefromjpeg의 <img> 태그를 받으시겠습니까?

여기에 텍스트를 쓰는 데 사용하는 코드가 있습니다.

HTML 코드 :

 <img id="image" src="<?php echo "upload_pic/" . $_FILES["image_file"]["name"]; ?>" alt="your_image" /> 
     <input type="button" name="save_image" id="save_image" value="Save Image" /> 
<input type="hidden" id="hidden_image_name" name="hidden_image_name" value="<?php echo $_FILES["image_file"]["name"]; ?>" /> 

jQuery를 코드 : 고급의

jQuery('#save_image').click(function(){ 
     var image_name = jQuery('#hidden_image_name').val(); 
     jQuery.ajax({ 
     url:'text_image.php', 
     data:'file='+image_name, 
     type:'get', 
     success:function(data){ 
      alert(data); 
     } 
    }); 
    }); 

text_image.php

<?php 

$file = 'upload_pic/'.$_GET['file']; 

/*** set the header for the image ***/ 
    header("Content-type: image/jpeg"); 

    /*** specify an image and text ***/ 
    $im = writeToImage($file, 'PHPRO rules again'); 
    //echo $im; 
    /*** spit the image out the other end ***/ 
    imagejpeg($im); 

    /** 
    * 
    * @Write text to an existing image 
    * 
    * @Author Kevin Waterson 
    * 
    * @access public 
    * 
    * @param string The image path 
    * 
    * @param string The text string 
    * 
    * @return resource 
    * 
    */ 
    function writeToImage($imagefile, $text){ 
    /*** make sure the file exists ***/ 
    if(file_exists($imagefile)) 
     {  
     /*** create image ***/ 
     $im = @imagecreatefromjpeg($imagefile); 

     /*** create the text color ***/ 
     $text_color = imagecolorallocate($im, 233, 14, 91); 

     /*** splatter the image with text ***/ 
     imagestring($im, 6, 25, 150, "$text", $text_color); 
     } 
    else 
     { 
     /*** if the file does not exist we will create our own image ***/ 
     /*** Create a black image ***/ 
     $im = imagecreatetruecolor(150, 30); /* Create a black image */ 

     /*** the background color ***/ 
     $bgc = imagecolorallocate($im, 255, 255, 255); 

     /*** the text color ***/ 
     $tc = imagecolorallocate($im, 0, 0, 0); 

     /*** a little rectangle ***/ 
     imagefilledrectangle($im, 0, 0, 150, 30, $bgc); 

     /*** output and error message ***/ 
     imagestring($im, 1, 5, 5, "Error loading $imagefile", $tc); 
     } 

    return $im; 
    } 
?> 

감사합니다!

+0

응답이 매우 복잡합니다. JFIF > 제작자 : gd-jpeg v1.0 (IJG JPEG v62 사용), 기본 품질 C \t \t $. ' "# (7) 01444'9 = 82 <.342C \t \t \t 2 22222222222222222222222222222222222222222222222222 !!"\t ! 1AQa "q2 # B R $ 3br – CuteBabyMannu

+2

"복잡하지 "않은 문자는 텍스트 모드로 볼 때 jpeg 이미지가 나타나는 모양입니다. – Spudley

+1

또한'$ _FILES [ "image_file"] [ "name"]'을 사용하면주의를 기울이십시오 - 파일의'name '은 클라이언트에 의해 결정되므로 공격 벡터로 사용할 수 있습니다. 슬래시가 포함되어 있으면 코드가 예상 한 것과 다른 파일을로드 할 수 있습니다. 사용하기 전에 위생 처리를했는지 또는 전혀 사용하지 않아야합니다 (즉, 업로드 한 파일의 고유 한 이름을 만드십시오). – Spudley

답변

0

window.location.href='text_image.php?file='+image_name; 이 저장되지 않기 때문에 jQuery를 사용하여 XMLHttpRequest (AJAX)를 보냅니다. 사용자는 브라우저 기록으로 돌아가서이 사이트를 다시 방문 할 수 있습니다.

또한 파일 이름을 변경하지 않았다고 생각합니다. move_uploaded_file($im,"upload_pic/angelina.jpg");

작은 팁 : 기능 전에 @ 연산자를 사용하지 마십시오! 그것은 성능 살인자입니다.

+0

이것은 내가 확인하고있는 텍스트 작성 코드 일 뿐이다. 나는 AJAX를 사용하여 이것을 할 것이다. – CuteBabyMannu

+0

이 새로 만든 파일의 이름이 무엇이고 tmp_name이 될 것이므로 – CuteBabyMannu

+0

아약스 용 코드를 업데이트했습니다. – CuteBabyMannu

1

변경할 때 IMG 소스를 다시로드하고 싶습니다. 그래서 당신은 무엇을해야하는지 캐싱을 방지하기 위해 더미 쿼리를 추가하여 IMG 태그의 SRC= 값을 대체하는 것입니다 :

jQuery('#save_image').click(function(){ 
    var image_name = jQuery('#hidden_image_name').val(); 
    jQuery.ajax({ 
    url:'text_image.php', 
    data:'file='+image_name, 
    type:'get', 
    success:function(data){ 
     jQuery('#image').attr('src', jQuery('#image') 
      .attr('src')+'?'+Math.random()); 
    } 
}); 
}); 

스크립트가 출력 아무것도 필요없는 PHP, 그냥 이미지 파일을 재 작성을

<?php 

    $file = 'upload_pic/'.$_GET['file']; 
    $im = writeToImage($file, 'PHPRO rules again'); 

    imageJPEG($im, $file, 95); // 95% quality 

    die(); 

    ... 
?> 

'성공'또는 '실패'를 나타내는 JSON을 출력 할 수 있습니다.

$_GET['file']이 유효하고 액세스 가능한 허용 이미지인지 확인하고 싶습니다.

$file = 'upload_pic/'.basename($_GET['file']); 
    if (!file_exists($file)) 
     // ...no such file... 
    if (false === getImageSize($file)) 
     // ...doesn't look like an image... 
    // etc. 

당신이 '자막'모두 원본과 이미지를 유지하려면, 당신은 create a new file에 필요한 또 다른 방법, 따라서 출력 그래서 새 이름 : 예를 들어, 당신은 기본 이름으로 파일을 강제로 수 jQuery는 SRC 속성을 대체 할 수 있습니다.

$new = 'upload_pic/'.uniqid().'.jpg'; 

    ...create the file and put $im into it, as above... 

    Header('Content-Type: application/json;charset=utf8'); 
    die(json_serialize(array("src" => $new))); 
    // Or if you don't want json_serialize (BUT THEN $new may only contain printable ASCII-7 characters that need no escaping. "[a-z][0-9]-_." if you want to be sure). 
    die("{\"src\":\"{$new}\"}"); 

jQuery를에, data 지금 그래서, $new가 포함됩니다 : 당신이 재하려는 경우

success:function(data){ 
     jQuery('#image').attr('src', data.src); 
    } 

(페이지, 당신은 다른 필드를 업데이트 할 필요가있을 수 있습니다 예를 들어

이미 자막이있는 이미지 캡션).

+0

첫 번째 방법을 사용하고 있지만 작동하지 않습니다. – CuteBabyMannu

+0

동일한'file ='매개 변수 값을 가진 브라우저 (즉, AJAX를 통하지 않는 PHP 스크립트)? 그것은 틀린 것에 대한 힌트를 줄 것입니다. – LSerni

+0

@iserni 첫 번째 방법은 잘 작동합니다 ... :) 덕분에 그것을 위해 주저하지만 두 번째 방법을 사용하고 있지만 두 번째 방법으로 새 ​​이미지를 만드는 새로운 이미지를 만들고 있지만이 이미지가 비어 있습니다. **이 코드는 ** text_image.php **에서 변경합니다. '$ unique_id = rand(); $ file = 'upload_pic /'.$ unique_id. $ _ GET [ '파일']; ' 및 주 파일에서이 코드 'jQuery ('image'). attr ('src', data);' – CuteBabyMannu

관련 문제