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

时间:2017-09-19 11:26:46

标签: php image imagesource

我有一个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的图像。但实际上,我不仅要收到文件名,还要收到图片。所以,真正的代码是

$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.

如何根据'数据创建:image / jpeg ...'在PHP中串起一个有效的图像?

编辑1:我在上面的代码中添加了一行,以确定它不是another question的可能副本:

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

编辑2:我修改了代码,以便删除文件:

$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

编辑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.";
}

2 个答案:

答案 0 :(得分: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 ).'" />';

如果您有兴趣,我几年前创建了一个处理这些内容的Image类,请参阅此处https://github.com/delboy1978uk/image/blob/master/src/Image.php以及关于它的博客https://delboy1978uk.wordpress.com/2014/12/01/outputting-images-as-base64-encoded-strings/

答案 1 :(得分:0)

问题解决了!!以下是获取浏览器缓存图像的代码。将其发送到请求的服务器位置。从服务器取回图像,结果是相同的图像。首先是JavaScript代码:

[…]
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.";
}