embed_images.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. #!/usr/bin/env python3
  2. """
  3. 将features_visualization.html中的所有图片转换为base64编码,生成可独立分享的HTML文件
  4. """
  5. import base64
  6. import os
  7. import json
  8. from pathlib import Path
  9. def image_to_base64(image_path):
  10. """将图片文件转换为base64编码的data URI"""
  11. try:
  12. with open(image_path, 'rb') as f:
  13. image_data = f.read()
  14. b64_data = base64.b64encode(image_data).decode('utf-8')
  15. # 根据文件扩展名确定MIME类型
  16. ext = Path(image_path).suffix.lower()
  17. mime_types = {
  18. '.jpg': 'image/jpeg',
  19. '.jpeg': 'image/jpeg',
  20. '.png': 'image/png',
  21. '.gif': 'image/gif',
  22. '.webp': 'image/webp'
  23. }
  24. mime_type = mime_types.get(ext, 'image/jpeg')
  25. return f"data:{mime_type};base64,{b64_data}"
  26. except Exception as e:
  27. print(f"Error converting {image_path}: {e}")
  28. return None
  29. def main():
  30. base_dir = Path(__file__).parent
  31. # 读取原始HTML文件
  32. html_file = base_dir / 'features_visualization.html'
  33. with open(html_file, 'r', encoding='utf-8') as f:
  34. html_content = f.read()
  35. # 创建图片映射字典
  36. image_map = {}
  37. # 1. 转换原始图片 (input/*.jpg)
  38. print("Converting original images...")
  39. input_dir = base_dir / 'input'
  40. for i in range(1, 10):
  41. img_name = f"img_{i}"
  42. img_path = input_dir / f"{img_name}.jpg"
  43. if img_path.exists():
  44. b64_uri = image_to_base64(img_path)
  45. if b64_uri:
  46. image_map[f"./input/{img_name}.jpg"] = b64_uri
  47. print(f" ✓ {img_name}.jpg")
  48. # 2. 转换特征图片 (output/features/*/*.png)
  49. print("\nConverting feature images...")
  50. features_dir = base_dir / 'output' / 'features'
  51. dimensions = [
  52. 'openpose_skeleton',
  53. 'depth_map',
  54. 'lineart_edge',
  55. 'color_palette',
  56. 'bokeh_mask',
  57. 'semantic_segmentation',
  58. 'color_distribution'
  59. ]
  60. for dim in dimensions:
  61. dim_dir = features_dir / dim
  62. if dim_dir.exists():
  63. print(f" {dim}:")
  64. for i in range(1, 10):
  65. img_name = f"img_{i}"
  66. img_path = dim_dir / f"{img_name}.png"
  67. if img_path.exists():
  68. b64_uri = image_to_base64(img_path)
  69. if b64_uri:
  70. image_map[f"./output/features/{dim}/{img_name}.png"] = b64_uri
  71. print(f" ✓ {img_name}.png")
  72. # 3. 替换HTML中的图片路径为base64
  73. print(f"\nTotal images converted: {len(image_map)}")
  74. print("\nGenerating embedded HTML...")
  75. # 创建JavaScript对象来存储base64图片
  76. js_image_map = "const imageMap = " + json.dumps(image_map, indent=2, ensure_ascii=False) + ";\n\n"
  77. # 在HTML中插入imageMap并修改图片加载逻辑
  78. # 找到 <script> 标签的位置
  79. script_start = html_content.find('<script>')
  80. if script_start == -1:
  81. print("Error: Could not find <script> tag")
  82. return
  83. script_start += len('<script>')
  84. # 插入imageMap定义
  85. html_content = html_content[:script_start] + "\n " + js_image_map + html_content[script_start:]
  86. # 修改图片路径使用逻辑 - 添加辅助函数
  87. helper_function = """ // 获取图片路径(优先使用base64,否则使用原路径)
  88. function getImageSrc(path) {
  89. return imageMap[path] || path;
  90. }
  91. """
  92. script_start = html_content.find('<script>')
  93. script_start += len('<script>')
  94. script_start = html_content.find('const imageMap', script_start)
  95. script_start = html_content.find('\n\n', script_start) + 2
  96. html_content = html_content[:script_start] + helper_function + html_content[script_start:]
  97. # 替换所有的图片src设置
  98. replacements = [
  99. # 原始图片
  100. ("card.onclick = () => openModal(`${basePath}/input/${imgName}.jpg`);",
  101. "card.onclick = () => openModal(getImageSrc(`${basePath}/input/${imgName}.jpg`));"),
  102. ("<img src=\"${basePath}/input/${imgName}.jpg\"",
  103. "<img src=\"${getImageSrc(`${basePath}/input/${imgName}.jpg`)}\""),
  104. # 特征图片
  105. ("img.src = featurePath;",
  106. "img.src = getImageSrc(featurePath);"),
  107. ("img.onclick = () => openModal(featurePath, imgName);",
  108. "img.onclick = () => openModal(getImageSrc(featurePath), imgName);"),
  109. # color_palette特殊处理
  110. ("img.src = `${basePath}/input/${imgName}.jpg`;",
  111. "img.src = getImageSrc(`${basePath}/input/${imgName}.jpg`);"),
  112. # modal中的图片
  113. ("modalOriginal.src = `${basePath}/input/${imgName}.jpg`;",
  114. "modalOriginal.src = getImageSrc(`${basePath}/input/${imgName}.jpg`);"),
  115. ("modalFeature.src = imagePath;",
  116. "modalFeature.src = imagePath;"), # imagePath已经是处理过的
  117. ("modalOriginal.src = imagePath;",
  118. "modalOriginal.src = imagePath;"), # imagePath已经是处理过的
  119. ]
  120. for old, new in replacements:
  121. html_content = html_content.replace(old, new)
  122. # 保存新的HTML文件
  123. output_file = base_dir / 'features_visualization_embedded.html'
  124. with open(output_file, 'w', encoding='utf-8') as f:
  125. f.write(html_content)
  126. print(f"\n✅ Successfully created: {output_file}")
  127. print(f"📦 File size: {len(html_content) / 1024 / 1024:.2f} MB")
  128. print("\n这个HTML文件现在可以独立分享,不需要附带图片文件夹。")
  129. if __name__ == '__main__':
  130. main()