dqkkrt8860 2017-09-19 03:26
浏览 60
已采纳

使用PHP将字符串转换为图像

I have a PHP script that should create a valid image file on server side. The following code runs fine:

  1. $filename = $_GET['filename'];
  2. // Only proceed if we got valid input
  3. if ($filename !== null) {
  4. echo "$filename is not null.";
  5. $image = @imagecreatetruecolor(10, 10)
  6. or die('Cannot Initialize new GD image stream');
  7. if (strpos($image, '/gif') !== false) {
  8. $image_type = "GIF";
  9. header('Content-Type: image/gif');
  10. $successful = imagegif($image, "./$filename");
  11. } else if (strpos($image, '/jpeg') !== false) {
  12. $image_type = "JPG";
  13. header('Content-Type: image/jpeg');
  14. $successful = imagejpeg($image, "./$filename");
  15. } else if (strpos($image, '/png') !== false) {
  16. $image_type = "PNG";
  17. header('Content-Type: image/png');
  18. $successful = imagepng($image, "./$filename");
  19. }
  20. if ($successful) {
  21. echo "Image written to '$filename'.";
  22. } else {
  23. echo "Could not write $image_type image to '$filename'.";
  24. }
  25. imagedestroy($image);
  26. echo "image destroyed.";
  27. } else {
  28. echo "$filename is null.";
  29. }

This works fine & an image with the $filename is created. But actually, I have to receive not only the file name but the image also. So, the real code is

  1. $filename = $_GET['filename'];
  2. $image = $_GET['image'];
  3. echo "file $filename = '$image'.";
  4. // Only proceed if we got valid input
  5. if ($filename !== null) {
  6. echo "$filename is not null.";
  7. if (strpos($image, '/gif') !== false) {
  8. $image_type = "GIF";
  9. header('Content-Type: image/gif');
  10. $successful = imagegif($image, "./$filename");
  11. } else if (strpos($image, '/jpeg') !== false) {
  12. $image_type = "JPG";
  13. header('Content-Type: image/jpeg');
  14. $successful = imagejpeg($image, "./$filename");
  15. } else if (strpos($image, '/png') !== false) {
  16. $image_type = "PNG";
  17. header('Content-Type: image/png');
  18. $successful = imagepng($image, "./$filename");
  19. }
  20. if ($successful) {
  21. echo "Image written to '$filename'.";
  22. } else {
  23. echo "Could not write $image_type image to '$filename'.";
  24. }
  25. imagedestroy($image);
  26. echo "image destroyed.";
  27. } else {
  28. echo "$filename is null.";
  29. }

This does not work, and the result is

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

How can I create from the 'data:image/jpeg … ' string a valid image in PHP?

EDIT 1: I added one line to the code above to see that it is not a possible duplicate of another question:

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

EDIT 2: I modified the code so that the file is deleted:

  1. $filename = $_GET['filename'];
  2. $image = $_GET['image'];
  3. // Only proceed if we got valid input
  4. if ($filename !== null) {
  5. echo "$filename is not null.";
  6. $image = base64_decode($image);
  7. $slash1 = strpos($image, '/');
  8. $image_type = substr($image, $slash1, strpos($image, ';') - $slash1);
  9. if (file_exists($filename)) unlink($filename);
  10. header('Content-Type: image/' . $image_type);
  11. switch ($image_type) {
  12. case "gif":
  13. $successful = imagegif($image, "./$filename");
  14. break;
  15. case "jpeg":
  16. case "jpg":
  17. $successful = imagejpeg($image, "./$filename");
  18. break;
  19. case "png":
  20. $successful = imagepng($image, "./$filename");
  21. break;
  22. }
  23. if ($successful) {
  24. echo "Image written to '$filename'.";
  25. } else {
  26. echo "Could not write $image_type image to '$filename'.";
  27. }
  28. imagedestroy($image);
  29. echo "image destroyed.";
  30. } else {
  31. echo "$filename is null.";
  32. }

But still, I get the reply Could not write image to 't.jpg'.

EDIT 3: This is what I pass to the two parameters:

?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: Modified the code according to suggestions of @delboy1978uk. Also, it is not correct that the passed filename includes the image file extension, as this should always correspond to the image type:

  1. $filename = $_GET['filename'];
  2. $image = $_GET['image'];
  3. echo "file $filename = '$image'.";
  4. // Only proceed if we got valid input
  5. if ($filename !== null) {
  6. $slash = strpos($image, '/') + 1;
  7. $image_type = substr($image, $slash, strpos($image, ';') - $slash);
  8. $comma = strpos($image, ',') + 1;
  9. $image = substr($image, $comma);
  10. $decoded_image = base64_decode($image);
  11. $image = imagecreatefromstring($decoded_image);
  12. echo "The image type is '$image_type'.";
  13. if (file_exists($filename)) {
  14. unlink($filename);
  15. echo "Deleted file '$filename'.";
  16. }
  17. header('Content-Type: image/' . $image_type);
  18. $filename .= '.' . $image_type;
  19. switch ($image_type) {
  20. case "gif":
  21. $successful = imagegif($image, "./$filename");
  22. break;
  23. case "jpeg":
  24. case "jpg":
  25. $successful = imagejpeg($image, "./$filename");
  26. break;
  27. case "png":
  28. $successful = imagepng($image, "./$filename");
  29. break;
  30. }
  31. if ($successful) {
  32. echo "Image written to '$filename'.";
  33. } else {
  34. echo "Could not write $image_type image to '$filename'.";
  35. }
  36. if (imagedestroy($image) === true) {
  37. echo "Image destroyed.";
  38. }
  39. } else {
  40. echo "$filename is null.";
  41. }

展开全部

  • 写回答

2条回答 默认 最新

  • dongqiuxu2270 2017-09-21 03:31
    关注

    The problem is solved!! Here is the code that gets the browser-cached image & sends it to a requested server location. Getting back the image from the server, it turns out to be the same image. First the JavaScript code:

    […]
    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();
    });
    

    For those interested, the PHP code follows:

    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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部