2014-12-03 92 views
0

有此功能将图像文件的内容编码为base64。图像文件的php base64_encode和glob无法开始工作

function data_uri($file_to_get_contents, $mime) { 
$contents = file_get_contents('../images/'. $file_to_get_contents); 
$base64 = base64_encode($contents); 
return ('data:' . $mime . ';base64,' . $base64); 
} 

实际位置(URL)是本

$val_img = '../images/2014-12-03/13-1-b5780ffc85f5f29d5ce43d1f4e38003f.gif'; 

我需要访问使用这样的URL回波图像(不.gif.jpg等)。

$val_img = '../images/2014-12-03/13-1-b5780ffc85f5f29d5ce43d1f4e38003f'; 

决定使用glob。并使用下面的代码。

$val_img = glob($val_img. '×.*'); 

也试过

$val_img = glob('×'. $val_img. '*'); 

有了这个看空数组

echo '<pre>', print_r($val_img, true), '</pre> $val_img <br/>'; 

而与此

echo '<img src='. data_uri($val_img , "../images"). ' alt="Image" >'; 

看到错误像Warning: file_get_contents(../images/Array) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: No such file or directory

错误通知在此$contents = file_get_contents('../images/'. $file_to_get_contents);行是错误的。

,但似乎不正确的数据与此$val_img = glob($val_img. '×.*');

什么是正确的代码?

这里是我的代码工作

function data_uri($file_to_get_contents, $mime) { 
$contents = file_get_contents('../images/'. $file_to_get_contents); 
$base64 = base64_encode($contents); 
return ('data:' . $mime . ';base64,' . $base64); 
} 

$val_img = '../images/2014-12-03/13-1-b5780ffc85f5f29d5ce43d1f4e38003f'; 

$val_img = glob($val_img. '*'); 

echo '<img src='. data_uri($val_img[0] , "../images"). ' alt="Image" >'; 
+1

什么是“x。*”?只需要'“$ val_img。*”'应该得到正确的'glob()'结果。 – 2014-12-03 06:55:19

+0

另外,你为什么首先使用'glob()'?因为你不知道扩展名?如果有两张图片的扩展名不同,会怎么样? – 2014-12-03 06:57:59

+0

是的,因为我不知道扩展名。图像名称将是唯一的。我称没有扩展名的图像名称。如果这样的名字存在,我想显示图像。这就是为什么我使用glob – user2118559 2014-12-03 07:01:09

回答

3

的问题是,你将数组传递给你的函数data_uri

glob返回一个数组。这意味着$val_img是一个数组,而不是一个字符串。但是当您将它作为参数$file_to_get_contents传递给data_uri时,您将它视为字符串。具体来说,你使用它作为一个字符串,在这一行:

$contents = file_get_contents('../images/'. $file_to_get_contents); 

最简单的方式来解决这个问题:更改您的来电data_uri,像这样:

echo '<img src='. data_uri($val_img[0] , "../images"). ' alt="Image" >'; 

另一种选择是循环阵列上方,像这样:

foreach($val_img as $one_img) { 
    echo '<img src='. data_uri($one_img , "../images"). ' alt="Image" >'; 
} 

编辑:您还可以在代码中的逻辑错误。不需要×角色(无论如何);你的文件名不包含一个。只要做到$val_img = glob($val_img. '.*');


附注:我已经发现,为了防止这类错误的最好方法是使用一个很好的IDE(我个人比较喜欢PHPStorm)和PHPDoc的块添加到您的所有功能描述参数类型。然后,如果当你的函数需要一个字符串时你试图传递一个数组,你将会从IDE得到一个警告。在开发时捕获这样的东西使得代码更加简洁,并帮助您避免将错误发布到野外。

+0

无法正常工作。如果我在'glob'之前打印'$ val_img',我会按预期的方式看到字符串。但是如果在'glob'后面打印,那么看到空数组。 – user2118559 2014-12-03 07:14:43

+0

为什么要添加'×'?不需要'×'字符(不管那是什么);你的文件名不包含一个。只要执行'$ val_img = glob($ val_img。'。*');' – 2014-12-03 07:20:43

+0

终于有了解决办法。将写在我的问题下面。感谢您的建议 – user2118559 2014-12-03 07:21:44