You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron应用从SQLite读取图片URL无法加载的排查与解决

Electron应用SQLite读取图片无法显示的问题解决

我开发了一个基于Electron.js的Web应用,使用HTML、CSS和JavaScript实现,通过以下代码将用户选择的图片转成Data URL后,和背景色一起保存到SQLite数据库,这部分功能正常:

const reader = new FileReader();
reader.onload = function () {
  const imageUrl = reader.result;
  query =
    "INSERT INTO QuizWindow VALUES('" +
    imageUrl +
    "','" +
    selectedColor +
    "');";
  db.queryStatement(query, (err, rows) => {
    if (err) {
      console.error(err.message);
    } else {
      rows.forEach((row) => {
        console.log(row); 
      });
    }
  });
};

reader.readAsDataURL(imageInput.files[0]);

但使用以下代码从SQLite读取数据并设置页面背景时,背景色能正常生效,图片却始终无法加载:

function LoadBackground() {
  var query = "SELECT * FROM QuizWindow ;";
  db.queryStatement(query, (err, rows) => {
    if (err) {
      console.error(err.message);
    } else {
      if (rows.length == 0) { // 无图片时加载默认图
        var imageUrl = "assets/images/quizBackGround.jpeg";
        document.body.style.backgroundImage = `url(${imageUrl})`;
        document.body.style.backgroundSize = "cover"; // 设置图片尺寸
        document.body.style.backgroundRepeat = "no-repeat";
      } else {
        rows.forEach((row) => {
          var selectedColor = row["BackGroundColor"]; 
          var imageUrl = row["ImagePath"];
          setBodyBackGround(imageUrl, selectedColor);
        });
      }
    }
  });
}

function setBodyBackGround(imageUrl, selectedColor) {
  document.body.style.backgroundColor = `${selectedColor}`;
  document.body.style.backgroundImage = `url(${imageUrl})`;
  document.body.style.backgroundSize = "40% 40%"; // 设置图片尺寸
  document.body.style.backgroundRepeat = "no-repeat"; // 禁止重复
  document.body.style.backgroundPosition = "center center"; // 居中显示
}

排查发现:控制台能正常打印出图片URL,且直接使用const imageUrl = reader.result;设置图片时显示正常,说明数据读取和存储都没有问题。


问题解决

代码逻辑本身无错误,问题出在*backgroundSize: "40% 40%"*这个CSS设置上。修改setBodyBackGround函数的背景尺寸属性后,图片正常显示:

function setBodyBackGround(imageUrl, selectedColor) {
  console.log("download file length " + imageUrl.length);
  document.body.style.backgroundColor = `${selectedColor}`;
  document.body.style.backgroundImage = `url(${imageUrl})`;
  document.body.style.backgroundSize = "50rem 20rem"; // 设置图片尺寸
  document.body.style.backgroundRepeat = "no-repeat"; // 禁止重复
  document.body.style.backgroundPosition = "left 45% top -15%"; // 调整位置
}

内容的提问来源于stack exchange,提问作者V M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 09:05:30