在javascript中,我通过将on-change方法绑定到文件输入并使用以下代码将文件数据保存到另一个输入来读取文件数据
$("#release_cover_custom").on('change', function (evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
$("#release_cover_custom_data").val(e.target.result);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
});
为什么我使用上面的代码?来存储图像数据,因为我有一个表单,我提供了稍后发送的电子邮件模板的设置,我必须提供在电子邮件中使用的背景图像,我需要在保存表单或上传图像之前预览包含所有设置的电子邮件以及提供的背景图像,因此我读取图像数据,将其保存到输入然后打开模态窗口以预览电子邮件并发布所有必要的变量,包括图像数据,然后在css中以下列方式使用,以在我的php视图文件中应用如下所示的背景图像
background-image:url('" . $background_image . "') !important;
现在我想通过php实现相同的功能,意味着如果我将图像保存到路径并且我想要读取图像数据并使用它,就像我使用javascript一样将其传递给css属性,
我尝试使用base64_encode(file_get_contents('path/to/file'))
但是图像数据的编码似乎有所不同,因为我不会使用其他方法在php中实现背景图像。
答案 0 :(得分:1)
@quagaar回复帮我解决了问题并取代了以下
$background_image=base64_encode(file_get_content('/path/to/file'));
带
$background_image='data:image/png;base64,'.base64_encode(file_get_content('/path/to/file'));
一切都按预期正常工作。
编辑:
我之间只处理图像,如果你只使用图像,你需要mime类型(例如标题,或者像我的情况),那么这是一种快速可靠的技术:
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));
即使您重命名图像文件,它也会输出真实的图像mime类型。