最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用JavaScript將PNG格式圖片轉(zhuǎn)為BMP格式的完整實(shí)現(xiàn)代碼

 更新時間:2025年12月26日 09:14:25   作者:還是大劍師蘭特  
這篇文章主要介紹了如何使用JavaScript將PNG圖片轉(zhuǎn)換為BMP格式,通過Canvas讀取PNG像素?cái)?shù)據(jù),并按照BMP文件格式規(guī)范組裝字節(jié)數(shù)據(jù),最終生成BMP格式的Blob/文件,需要的朋友可以參考下

在瀏覽器端使用 JavaScript 將 PNG 圖片轉(zhuǎn)換為 BMP 格式,核心思路是:先通過 Canvas 讀取 PNG 像素?cái)?shù)據(jù),再按照 BMP 文件格式規(guī)范組裝字節(jié)數(shù)據(jù),最終生成 BMP 格式的 Blob/文件。以下是完整可運(yùn)行的實(shí)現(xiàn)方案:

核心知識點(diǎn)

  1. BMP 文件結(jié)構(gòu):由文件頭(14字節(jié))、信息頭(40字節(jié))、像素?cái)?shù)據(jù)三部分組成;
  2. 像素格式轉(zhuǎn)換:Canvas 讀取的像素是 RGBA 格式,需轉(zhuǎn)為 BMP 要求的 BGRA(小端序,且忽略 Alpha 通道);
  3. 字節(jié)對齊:BMP 每行像素?cái)?shù)據(jù)需按 4 字節(jié)對齊,不足補(bǔ) 0。

完整實(shí)現(xiàn)代碼

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>PNG 轉(zhuǎn) BMP</title>
</head>
<body>
    <input type="file" id="fileInput" accept="image/png">
    <button id="convertBtn" disabled>轉(zhuǎn)換為 BMP</button>
    <script>
        // 全局變量存儲圖片數(shù)據(jù)
        let imageData = null;
        const fileInput = document.getElementById('fileInput');
        const convertBtn = document.getElementById('convertBtn');

        // 監(jiān)聽文件選擇
        fileInput.addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (!file || !file.type.includes('png')) {
                alert('請選擇 PNG 格式圖片');
                return;
            }
            // 讀取圖片并獲取像素?cái)?shù)據(jù)
            imageData = await getImageData(file);
            convertBtn.disabled = false;
        });

        // 監(jiān)聽轉(zhuǎn)換按鈕點(diǎn)擊
        convertBtn.addEventListener('click', () => {
            if (!imageData) return;
            // 轉(zhuǎn)換為 BMP 格式 Blob
            const bmpBlob = pngToBmp(imageData);
            // 下載文件
            downloadBlob(bmpBlob, 'converted.bmp');
        });

        /**
         * 讀取圖片文件并獲取 Canvas ImageData
         * @param {File} file - PNG 文件
         * @returns {Promise<ImageData>} 像素?cái)?shù)據(jù)
         */
        function getImageData(file) {
            return new Promise((resolve) => {
                const img = new Image();
                // 解決跨域問題(本地文件無需擔(dān)心,在線環(huán)境需確保圖片跨域權(quán)限)
                img.crossOrigin = 'anonymous';
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0);
                    resolve(ctx.getImageData(0, 0, img.width, img.height));
                };
                img.src = URL.createObjectURL(file);
            });
        }

        /**
         * 將 ImageData 轉(zhuǎn)換為 BMP 格式 Blob
         * @param {ImageData} imageData - Canvas 像素?cái)?shù)據(jù)
         * @returns {Blob} BMP 格式 Blob
         */
        function pngToBmp(imageData) {
            const { width, height, data } = imageData;
            const rowSize = Math.floor((24 * width + 31) / 32) * 4; // 每行字節(jié)數(shù)(4字節(jié)對齊)
            const pixelArraySize = rowSize * height; // 像素?cái)?shù)據(jù)總字節(jié)數(shù)
            const fileSize = 14 + 40 + pixelArraySize; // BMP 文件總大小

            // 創(chuàng)建 ArrayBuffer 存儲 BMP 數(shù)據(jù)(文件頭14 + 信息頭40 + 像素?cái)?shù)據(jù))
            const buffer = new ArrayBuffer(fileSize);
            const view = new DataView(buffer);

            // ---------------------- 1. 寫入 BMP 文件頭(14字節(jié)) ----------------------
            view.setUint8(0, 0x42); // 'B'
            view.setUint8(1, 0x4D); // 'M'
            view.setUint32(2, fileSize, true); // 文件總大小(小端序)
            view.setUint32(6, 0, true); // 保留字段
            view.setUint32(10, 14 + 40, true); // 像素?cái)?shù)據(jù)偏移量

            // ---------------------- 2. 寫入 BMP 信息頭(40字節(jié)) ----------------------
            view.setUint32(14, 40, true); // 信息頭大小
            view.setInt32(18, width, true); // 寬度
            view.setInt32(22, -height, true); // 高度(負(fù)數(shù)表示從上到下繪制)
            view.setUint16(26, 1, true); // 平面數(shù)
            view.setUint16(28, 24, true); // 位深度(24位,無Alpha)
            view.setUint32(30, 0, true); // 壓縮方式(0 = 不壓縮)
            view.setUint32(34, pixelArraySize, true); // 像素?cái)?shù)據(jù)大小
            view.setInt32(38, 2835, true); // 水平分辨率(像素/米,默認(rèn)值)
            view.setInt32(42, 2835, true); // 垂直分辨率(像素/米,默認(rèn)值)
            view.setUint32(46, 0, true); // 調(diào)色板顏色數(shù)
            view.setUint32(50, 0, true); // 重要顏色數(shù)

            // ---------------------- 3. 寫入像素?cái)?shù)據(jù)(BGRA 轉(zhuǎn) BGR,補(bǔ)對齊字節(jié)) ----------------------
            let offset = 14 + 40; // 像素?cái)?shù)據(jù)起始偏移
            for (let y = 0; y < height; y++) {
                for (let x = 0; x < width; x++) {
                    const idx = (y * width + x) * 4;
                    view.setUint8(offset++, data[idx + 2]); // B(藍(lán)色)
                    view.setUint8(offset++, data[idx + 1]); // G(綠色)
                    view.setUint8(offset++, data[idx]);     // R(紅色)
                    // 忽略 Alpha 通道(24位BMP無Alpha)
                }
                // 補(bǔ)充行對齊字節(jié)(每行必須是4的倍數(shù))
                const padding = (rowSize - (width * 3)) % 4;
                for (let p = 0; p < padding; p++) {
                    view.setUint8(offset++, 0);
                }
            }

            // 返回 BMP Blob
            return new Blob([buffer], { type: 'image/bmp' });
        }

        /**
         * 下載 Blob 文件
         * @param {Blob} blob - 要下載的 Blob
         * @param {string} fileName - 文件名
         */
        function downloadBlob(blob, fileName) {
            const a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            a.download = fileName;
            a.click();
            URL.revokeObjectURL(a.href); // 釋放內(nèi)存
        }
    </script>
</body>
</html>

使用說明

  1. 將上述代碼保存為 HTML 文件,用瀏覽器打開;
  2. 點(diǎn)擊文件選擇框,選擇要轉(zhuǎn)換的 PNG 圖片;
  3. 點(diǎn)擊「轉(zhuǎn)換為 BMP」按鈕,自動下載轉(zhuǎn)換后的 BMP 文件。

關(guān)鍵注意事項(xiàng)

  1. 跨域限制:如果在線使用,確保 PNG 圖片有跨域訪問權(quán)限(Access-Control-Allow-Origin),否則 Canvas 無法讀取像素?cái)?shù)據(jù);
  2. 位深度:示例實(shí)現(xiàn)的是 24 位 BMP(無 Alpha 通道),BMP 也支持 32 位帶 Alpha,但兼容性較差,如需支持可修改信息頭的位深度為 32,并保留 Alpha 通道;
  3. 性能:處理超大圖片(如 4K 以上)時,可能會有性能卡頓,可考慮分片處理;
  4. 兼容性:所有現(xiàn)代瀏覽器(Chrome、Firefox、Edge、Safari)均支持,IE 不支持 BlobDataView,需兼容 IE 需額外處理。

到此這篇關(guān)于使用JavaScript將PNG格式圖片轉(zhuǎn)為BMP格式的完整實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)JavaScript PNG格式轉(zhuǎn)為BMP格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

渑池县| 淮阳县| 罗田县| 阿拉善右旗| 滨海县| 霍林郭勒市| 尤溪县| 丹巴县| 阿尔山市| 麟游县| 西丰县| 塔河县| 道孚县| 大埔县| 九龙城区| 台安县| 浮山县| 华坪县| 壤塘县| 永城市| 峨眉山市| 黄冈市| 万安县| 云梦县| 连云港市| 民县| 怀化市| 鄂托克前旗| 江城| 叶城县| 资兴市| 木兰县| 美姑县| 瑞安市| 绥中县| 稻城县| 乌审旗| 惠安县| 晋江市| 岳阳县| 大港区|