2017-09-19 16 views
0

서버 측에 유효한 이미지 파일을 만들어야하는 PHP 스크립트가 있습니다. 다음 코드는 잘 실행 :이 $ 파일 이름을 가진 이미지가 생성되는 미세 & 작동PHP로 문자열을 이미지로 변환

$filename = $_GET['filename']; 

// Only proceed if we got valid input 
if ($filename !== null) { 
    echo "$filename is not null."; 
    $image = @imagecreatetruecolor(10, 10) 
       or die('Cannot Initialize new GD image stream'); 

    if (strpos($image, '/gif') !== false) { 
     $image_type = "GIF"; 
     header('Content-Type: image/gif'); 
     $successful = imagegif($image, "./$filename"); 
    } else if (strpos($image, '/jpeg') !== false) { 
     $image_type = "JPG"; 
     header('Content-Type: image/jpeg'); 
     $successful = imagejpeg($image, "./$filename"); 
    } else if (strpos($image, '/png') !== false) { 
     $image_type = "PNG"; 
     header('Content-Type: image/png'); 
     $successful = imagepng($image, "./$filename"); 
    } 

    if ($successful) { 
     echo "Image written to '$filename'."; 
    } else { 
     echo "Could not write $image_type image to '$filename'."; 
    } 
    imagedestroy($image); 
    echo "image destroyed."; 
} else { 
    echo "$filename is null."; 
} 

. 그러나 사실, 파일 이름뿐만 아니라 이미지도 수신해야합니다. 그래서, 나는에서 만드는 방법을 실제 코드는

$filename = $_GET['filename']; 

$image = $_GET['image']; 

echo "file $filename = '$image'."; 

// Only proceed if we got valid input 
if ($filename !== null) { 
    echo "$filename is not null."; 

    if (strpos($image, '/gif') !== false) { 
     $image_type = "GIF"; 
     header('Content-Type: image/gif'); 
     $successful = imagegif($image, "./$filename"); 
    } else if (strpos($image, '/jpeg') !== false) { 
     $image_type = "JPG"; 
     header('Content-Type: image/jpeg'); 
     $successful = imagejpeg($image, "./$filename"); 
    } else if (strpos($image, '/png') !== false) { 
     $image_type = "PNG"; 
     header('Content-Type: image/png'); 
     $successful = imagepng($image, "./$filename"); 
    } 

    if ($successful) { 
     echo "Image written to '$filename'."; 
    } else { 
     echo "Could not write $image_type image to '$filename'."; 
    } 
    imagedestroy($image); 
    echo "image destroyed."; 
} else { 
    echo "$filename is null."; 
} 

이 작동하지 않습니다이며, 결과는

file t.png = 'data:image/jpeg;base64,/9j/4AAQSkZJ … qA/Cz//Z'.t.png is not null.Image written to 't.png'.image destroyed. 

입니다 '데이터 : 이미지/JPEG를 ...'문자열은 PHP에서 유효한 이미지?

EDIT 1

// Only proceed if we got valid input 
if ($filename !== null) { 
    echo "$filename is not null."; 
    $image = base64_decode($image); // <<<< 

EDIT 2 : 파일이되도록 I 코드를 수정는 I 위가 another question의 중복 가능성이 아니라는 것을 확인하기 위해 코드에 한 줄씩 추가 삭제됨 :

$filename = $_GET['filename']; 

$image = $_GET['image']; 

// Only proceed if we got valid input 
if ($filename !== null) { 
    echo "$filename is not null."; 
    $image = base64_decode($image); 
    $slash1 = strpos($image, '/'); 

    $image_type = substr($image, $slash1, strpos($image, ';') - $slash1); 

    if (file_exists($filename)) unlink($filename); 

    header('Content-Type: image/' . $image_type); 

    switch ($image_type) { 
     case "gif": 
      $successful = imagegif($image, "./$filename"); 
      break; 
     case "jpeg": 
     case "jpg": 
      $successful = imagejpeg($image, "./$filename"); 
      break; 
     case "png": 
      $successful = imagepng($image, "./$filename"); 
      break; 
    } 

    if ($successful) { 
     echo "Image written to '$filename'."; 
    } else { 
     echo "Could not write $image_type image to '$filename'."; 
    } 
    imagedestroy($image); 
    echo "image destroyed."; 
} else { 
    echo "$filename is null."; 
} 

그래도 답변은 Could not write image to 't.jpg'입니다.

편집 3 :이 내가 두 개의 매개 변수로 전달할 것입니다 :

?filename=t.jpg&image=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/7AARRHVja3kAAQAEAAAAPAAA/+0ALFBob3Rvc2hvcCAzLjAAOEJJTQQlAAAAAAAQAAAAAAAAAAAAAAAAAAAAAP/bAEMAAgEBAgEBAgICAgICAgIDBQMDAwMDBgQEAwUHBgcHBwYHBwgJCwkICAoIBwcKDQoKCwwMDAwHCQ4PDQwOCwwMDP/bAEMBAgICAwMDBgMDBgwIBwgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAEAAQMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APA6KKK/qA/Cz//Z 

EDIT 4 :는 @ delboy1978uk의 제안에 따라 코드를 수정. 당신은 이미 출력을 전송 한 페이지에 헤더를 보내려고

$filename = $_GET['filename']; 

$image = $_GET['image']; 

echo "file $filename = '$image'."; 

// Only proceed if we got valid input 
if ($filename !== null) { 
    $slash = strpos($image, '/') + 1; 

    $image_type = substr($image, $slash, strpos($image, ';') - $slash); 
    $comma = strpos($image, ',') + 1; 

    $image = substr($image, $comma); 

    $decoded_image = base64_decode($image); 

    $image = imagecreatefromstring($decoded_image); 

    echo "The image type is '$image_type'."; 

    if (file_exists($filename)) { 
     unlink($filename); 
     echo "Deleted file '$filename'."; 
    } 

    header('Content-Type: image/' . $image_type); 
    $filename .= '.' . $image_type; 

    switch ($image_type) { 
     case "gif": 
      $successful = imagegif($image, "./$filename"); 
      break; 
     case "jpeg": 
     case "jpg": 
      $successful = imagejpeg($image, "./$filename"); 
      break; 
     case "png": 
      $successful = imagepng($image, "./$filename"); 
      break; 
    } 

    if ($successful) { 
     echo "Image written to '$filename'."; 
    } else { 
     echo "Could not write $image_type image to '$filename'."; 
    } 

    if (imagedestroy($image) === true) { 
     echo "Image destroyed."; 
    } 
} else { 
    echo "$filename is null."; 
} 
+0

가능한 중복 (HTTPS를 [데이터 URL에서 이미지 만들기] : // 유래.com/questions/4672392/create-image-from-data-url) – iainn

답변

0

문제가 해결되었습니다! 다음은 브라우저 캐시 이미지 &을 요청 된 서버 위치로 전송하는 코드입니다. 서버에서 이미지를 가져 오는 것은 동일한 이미지로 판명됩니다. 먼저 자바 스크립트 코드 : 관심있는 사람들을 위해

[…] 
var parameters = { 
    […], 
    headerImageLocation: '', 
    image: new Image(), 
    […], 
}; 

if (strings.hasMinimalLength(blobURL, 9)) { 
    this.getBlobFromURL(blobURL).then(this.fromBlobToBase64).then(function(result) { 
     parameters['image'].src = result; 
     parameters['headerImageLocation'] = './' + strings.generateID(); 

     server.continueWithNewsTicker(parameters); 
    }); 
} else { 
    this.continueWithNewsTicker(parameters); 
} 

// Prototype "MainServer": 
MainServer.method('continueWithNewsTicker', function(parameters) { 
    var url = server.ServiceTest + 'saveHeaderImage.php'; 

    if (strings.hasMinimalLength(parameters['headerImageLocation'], 1)) { 
     var formData = new FormData(); 

     formData.append('filename', parameters['headerImageLocation']); 
     formData.append('image', parameters['image'].src); 

     this.uploadFile(formData, url); 
    } 
    […] 
}); 

// Prototype "Server": 
Server.method('uploadFile', function (data, url) { 
    var xhr = new XMLHttpRequest(); // AJAX request 

    xhr.open('POST', url); 
    xhr.send(data); 
}); 

// Prototype "Strings": 
Strings.method('generateID', function() { 
    function s4() { 
     return Math.floor((1 + Math.random())*0x10000) 
      .toString(16) 
      .substring(1); 
    } 
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + 
     s4() + '-' + s4() + s4() + s4(); 
}); 

는 PHP 코드는 다음과 같습니다의

ini_set('display_errors', 1); 
error_reporting(E_ALL); 

// Get the input data safely 
$filename = $_POST['filename']; 
$image = $_POST['image']; 

// Only proceed if we got valid input 
if ($filename !== null) { 
    // Prepare to remove "header" information: 
    $comma = strpos($image, ',') + 1; 
    $slash = strpos($image, '/') + 1; 
    // The image type will also determine the file extension 
    $image_type = substr($image, $slash, strpos($image, ';') - $slash); 
    // Remove "header" information from rest of image: 
    $image = substr($image, $comma); 

    $decoded_image = base64_decode($image); 
    $filename .= '.' . $image_type; 

    if (file_exists($filename)) unlink($filename); 

    $successful = file_put_contents($filename, $decoded_image); 

    if ($successful) { 
     echo "Image written to '$filename'."; 
    } else { 
     echo "Could not write $image_type image to '$filename'."; 
    } 
} else { 
    echo "$filename is null."; 
} 
1

이 항상 이미지 유형에 해당한다으로 또한, 전달 된 파일 이름 이미지 파일 확장자를 포함 올바르지 않습니다 .

파일에서로드하는 경우 imagecreatefromjpeg() 및 해당하는 GIF 및 PNG를 사용해야합니다.

http://php.net/manual/en/function.imagecreatefromjpeg.php

$img = imagecreatefromjpeg($file); 
말 그대로 <image> 태그에서 에코에, 실제 문자열 데이터를 얻을 출력 버퍼링을 사용하려면 : 당신이 관심이 있다면

ob_start(); 
imagejpeg($img) 
$image = ob_get_clean(); 
echo '<img src="data:image/jpeg;base64,' . base64_encode($i).'" />'; 

, 나는이 문제를 처리하는 몇 년 전 이미지 클래스를 만든 물건, 여기를 참조하십시오 https://github.com/delboy1978uk/image/blob/master/src/Image.php 및 그것에 대한 블로그 https://delboy1978uk.wordpress.com/2014/12/01/outputting-images-as-base64-encoded-strings/

+0

오, 감사합니다! 그러나'imagecreatefromjpeg'는 실행할 이미지 파일의 파일 이름이 필요합니다. 서버 디스크에 파일을 생성해야하는 GET 요청이있는 텍스트 데이터를 보내고 있습니다. 나는. 서버 쪽에서 클라이언트 쪽에서 만든 파일을 복제하려고합니다. – Sae1962

+0

아아아, 나는 두 번째 부분에서 당신이 열 수있는 파일 이름을 보내고 있다고 생각했습니다! 이 경우 파일이 이미 존재하면 실패하는 것 같습니다. 'file_exists()'를 시도해보고 어쩌면 제거하겠습니까? – delboy1978uk

+0

코드가 수정되었지만 파일이 작성되지 않았으므로 잘못된 것이 있습니다. – Sae1962