前段时间我去爬山,回来写了文章:朱雀国家森林公园痛苦一日游
上传图片的时候发现当前时代的浏览器并不支持浏览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-缆车

标签: none

已有 2 条评论

  1. EricQwQ EricQwQ

    华为edge,图片跟我转圈圈了五分钟😂好怪呀

    1. 本地软编解码,我的设备普遍在几秒内完成转换。

添加新评论