从WSL2(Ubuntu 20.04)目录加载图像到Windows网页时的问题

-1 投票
1 回答
47 浏览
提问于 2025-04-14 18:27

简而言之: 在基于Windows的Chrome浏览器中,可以顺利加载WSL2中的HTML文件,但由于某种解析问题,嵌入的WSL2中的图片无法加载,因为文件路径前面没有加上“Ubuntu”。通过网页检查手动修改图片的文件路径可以暂时解决这个问题,但在生成HTML页面时加上“Ubuntu”并不能解决这个问题。

具体情况如下: 在处理完我的数据后,我想通过Jupyter Notebook在网页上展示结果。 所以,我运行了以下代码:

import pandas as pd
from IPython.core.display import HTML


# For showing images in Pandas DF
def path_to_image_html(path, windows = True):
    return '<img src="'+ path + '" width="250" >'

df = pd.DataFrame(columns = ['img_guid', 'img_text', 'img_original', 'img_processed', 'img_filestring'])

for image_name in images.items():
    img_processed = process(img_original)
    data_output_dict = {
        'img_guid': [img_guid], 
        'img_text': [text.rstrip()], 
        'img_original': [path_to_image_html(img_original)],
        'img_processed': [path_to_image_html(img_processed)],
        'img_filestring': [img_filestring]
    }
    df_temp = pd.DataFrame(data_output_dict)
    df = pd.concat([df, df_temp], ignore_index=True)

html_output = HTML(df.to_html(escape=False))

with open('html_file.html', 'w') as f: f.write(html_output.data)

然而,结果是这样的:(请查看Imgur上的图片 --> 网页示例

网页的样子是我想要的,除了图片没有加载。它们的文件路径是 file://wsl.localhost/home/Oaknut/ProjectDir/img_dir/example_image.png,而HTML文件的位置是 file://wsl.localhost/Ubuntu/home/Oaknut/ProjectDir/html_file.html - 手动在浏览器中使用HTML检查工具添加缺失的 Ubuntu 部分后,图片就能显示出来,但这显然不是解决问题的方法。在上面提到的 path_to_image_html 函数中添加 if windows: path = 'Ubuntu' + path 也无法解决问题,因为这样会导致图片在重新编译的HTML文件中的文件位置变成 file://wsl.localhost/Ubuntu/home/Oaknut/ProjectDir/Ubuntu/home/Oaknut/ProjectDir/img_dir/example_image.png

  • 系统设置:使用Windows 11和WSL2,通过安装在Windows上的VScode运行WSL2中的Python 3.8(我需要CUDA,所以使用WSL2),并在Windows上使用Chrome浏览器。

补充说明: img_original 变量(或者 img_processed 变量)中的值是 /home/Oaknut/ProjectDir/img_dir/example_img.png(显然不是原始名称,但为了最小工作示例遵循相同的文件和文件夹结构)。

1 个回答

0

你能用原始字符串来添加一个 Ubuntu 文件夹吗?类似这样:

if windows:
   path = rf'Ubuntu{path}'

撰写回答