分类 JavaScript/Node.js 下的文章

前段时间我去爬山,回来写了文章:朱雀国家森林公园痛苦一日游
上传图片的时候发现当前时代的浏览器并不支持浏览HEIF格式的图片,但是这一标准在苹果和许多较新安卓设备上都已经开始推广,并且压缩率不错,所以能不能想办法让浏览器显示HEIF格式的图片呢?

找到所需开源项目:

hoppergee/heic-to Convert HEIC/HEIF images to JPEG, PNG in browser
我的需求显然早就有人在做了,这个项目利用javascript提供了一个在前端将HEIF格式图片转换成jpeg/png的方案。

引用heic-to

工作原理:

  1. 自动检测所有带有.heic或.HEIC扩展名的图片
  2. 使用fetch API获取原始HEIC文件
  3. 在浏览器中转换为JPEG格式
  4. 替换图片的src属性显示转换后的图片
<script type="module">
// 导入CSP安全版本的HEIC转换模块 需要支持ES6特性
import { heicTo } from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/csp/heic-to.js';

document.addEventListener('DOMContentLoaded', async function() {
    // 检查浏览器是否支持所需API
    if (!window.fetch || !window.URL || !window.Blob) {
        console.warn('浏览器不支持HEIC转换所需API');
        return;
    }
    
    // 处理HEIC图片转换
    async function processHEICImages() {
        const images = document.querySelectorAll('img[src$=".heic"], img[src$=".HEIC"]');
        if (images.length === 0) return;
        
        console.log(`找到 ${images.length} 张HEIC图片,开始转换...`);
        
        for (const img of images) {
            const src = img.src;
            const originalAlt = img.alt || '';
            const originalClass = img.className;
            
            try {
                // 添加加载状态
                img.alt = 'HEIC图片转换中...';
                img.classList.add('heic-loading');
                
                // 获取HEIC文件
                const response = await fetch(src);
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
                
                const blob = await response.blob();
                
                // 转换为JPEG
                const jpegBlob = await heicTo({
                    blob: blob,
                    type: "image/jpeg",
                    quality: 0.8
                });
                
                // 创建对象URL并替换
                const jpegUrl = URL.createObjectURL(jpegBlob);
                img.onload = function() {
                    URL.revokeObjectURL(jpegUrl); // 释放内存
                    img.classList.remove('heic-loading');
                    img.classList.add('heic-converted');
                };
                img.src = jpegUrl;
                img.alt = originalAlt;
                img.className = originalClass;

            } catch (err) {
                console.error('HEIC转换失败:', err);
                img.alt = originalAlt + ' [HEIC转换失败]';
                img.classList.remove('heic-loading');
                img.classList.add('heic-error');
            }
        }
    }
    
    await processHEICImages();
});
</script>

<style>
.heic-loading {
    position: relative;
    min-height: 100px;
    background: #f5f5f5 url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" stroke="%233498db" stroke-width="8" fill="none" stroke-dasharray="62.8 188.8"><animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="1s" values="0 50 50;360 50 50" keyTimes="0;1"></animateTransform></circle></svg>') no-repeat center;
    background-size: 50px;
}
.heic-converted {
    border: 2px solid #2ecc71;
}
.heic-error {
    border: 2px dashed #e74c3c;
}
</style>

使用方法:

你可以引用上面的代码到任意html页面,通常我们把他放在header或footer里。
在Typecho上我们可以把它放在主题文件的: header.php 中

本文代码已在Github以MIT协议开源,感谢自由软件与开源社区!
DisplayMyHEIC

测试图片

测试图片1-人物
测试图片2-缆车

感谢那几位大佬指点,给他们发红包感谢了。(其实就几毛钱,但是我QQ也就剩下这么多...... )

方法1

str = '[CQ:at,qq=1052757154,text=@筱可儿]';
qq = str.match(/qq=(\d+)/);
console.log(qq)

输出:

[
  'qq=1052757154',
  '1052757154',
  index: 7,
  input: '[CQ:at,qq=1052757154,text=@筱可儿]',
  groups: undefined
]

QQUID=qq[1]

方法2

str = '[CQ:at,qq=1052757154,text=@筱可儿]';
qq=str.match(/(?<=qq=)\d+|(?<=text=@).+(?=\])|(?<=\]).*/g);
console.log(qq)

输出:

[ '1052757154', '筱可儿', '' ]

QQUID=qq[0],nickname=qq[1]

为什么用到这个?因为我想要得到形如text 123456这串文字中的123456部分,延伸一下用途,这可以用来处理qbot接收到的指定格式命令的消息,得到命令标识后的命令部分。

split()

split()把一个字符串分割成字符串数组:
标准语法:string.split(separator,limit)

  • separator:可选。 字符串或正则表达式,从该参数指定的地方分割 string Object。
  • limit:可选。 该参数可指定返回的数组的最大长度。如果设置了该参数,返回的子串不会多于这个参数指定的数组。如果没有设置该参数,整个字符串都会被分割,不考虑它的长度。

    示例

    var message = "xiao 12345"
    var array = message.split(" ") //此处使用一个空格作为分隔符即“separato”,如果使用空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。
    console.log(array) //直接输出数组array
    console.log(array[0]) //输出数组array的第一个元素
    console.log(array[1]) //输出数组array的第二个元素
    -----------------输出结果--------------------
    [ 'xiao', '12345' ]
    xiao
    12345

    如果你在visual sutdio code中执行出现报错(没有可用的调试程序,无法发送“variables”),可以安装Code Runner 使用组合键Ctrl Alt N直接运行,也可以在launch.json文件内program下面加一行"console": "integratedTerminal" ,此语句设置 启动调试目标的位置为integratedTerminal即 VS Code 的集成终端。

感谢ACGP社团社长MartinKay提供方案指导。

部分内容使用了https://www.runoob.com/jsref/jsref-split.html 提供的资料