将图像转换为字节内容而不上传图像

时间:2013-08-28 11:37:55

标签: php html image

我有一个html表单和一个上传文件控件

<form action="action.php" method="post" enctype="multipart/form-data"> 
  <input type="file" name="file">   
  <input type="submit" value="submit"> 
</form>

我希望在不将文件上传到服务器的情况下获取图像“base64_encode()”的字节内容

3 个答案:

答案 0 :(得分:0)

您可以尝试使用HTML5:

创建画布,将图像加载到画布中,然后使用toDataURL()获取base64表示。

注意:未经测试

修改

http://tutorials.jenkov.com/html5-canvas/todataurl.html

答案 1 :(得分:0)

在这里,你肯定不兼容旧的IE,不是100正确,因为它没有正确处理多个文件(你需要img和画布的唯一id-s),但是......

<html>
    <body>
    <input type="file" id="files" name="files[]" multiple />
    <output id="list"></output>

<script>
function handleFileSelect(evt) {
    var files = evt.target.files;
    for (var i = 0, f; f = files[i]; i++) 
    {
        if (!f.type.match('image.*')) 
        continue;

    var reader = new FileReader();

    reader.onload = (function(theFile)
    {
        return function(e) {
            var span = document.createElement('span');
            span.innerHTML = ['<img id="ex1" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
            document.getElementById('list').insertBefore(span, null);

            var img  = document.getElementById("ex1");

            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);

            var dataUrl = canvas.toDataURL();
            alert(dataUrl);

            };
        })(f);
        reader.readAsDataURL(f);
    }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
    </body>
</html>

答案 2 :(得分:-1)

以下摘自this答案:

$raw_data = file_get_contents('php://input');
$boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));

// Fetch each part
$parts = array_slice(explode($boundary, $raw_data), 1);
$data = array();
$base64_encoded = NULL;

foreach ($parts as $part) {
    // If this is the last part, break
    if ($part == "--\r\n") break; 

    // Separate content from headers
    $part = ltrim($part, "\r\n");
    list($raw_headers, $body) = explode("\r\n\r\n", $part, 2);

    // Parse the headers list
    $raw_headers = explode("\r\n", $raw_headers);
    $headers = array();
    foreach ($raw_headers as $header) {
        list($name, $value) = explode(':', $header);
        $headers[strtolower($name)] = ltrim($value, ' '); 
    } 

    // Parse the Content-Disposition to get the field name, etc.
    if (isset($headers['content-disposition'])) {
        $filename = null;
        preg_match(
            '/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/', 
            $headers['content-disposition'], 
            $matches
        );
        list(, $type, $name) = $matches;
        isset($matches[4]) and $filename = $matches[4]; 

        // handle your fields here
        switch ($name) {
            // this is a file upload
            case 'userfile':
                 $base64_encoded = base64_encode($body);
                 break;

            // default for all other files is to populate $data
            default: 
                 $data[$name] = substr($body, 0, strlen($body) - 2);
                 break;
        } 
    }
}

echo $base64_encoded;

警告

上面的代码使用substr()来搜索边界并通过正则表达式获取字段名称。

如果您想更有效地执行此操作,则必须实施快速字符串搜索算法,例如Boyer-Moore

将整个内容存储在内存中。您可能希望限制最大上传大小等。