1.0.55 • Published 1 year ago

image-magic-adapter v1.0.55

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

ImageMagicAdapter

一个功能丰富的图片处理库,支持图片压缩、格式转换、添加水印以及修改图片尺寸。

在线演示-官网地址: http://luckycola.com.cn/public/dist/imageTool.html

安装

npm install image-magic-adapter

引入项目

import ImageMagicAdapter from 'image-magic-adapter';
let ImageCompressorCls = ImageMagicAdapter.ImageCompressorCls;
let ImageResizerCls = ImageMagicAdapter.ImageResizerCls;

使用示例

图片压缩

HTML 部分:

 <h4>图片压缩Demo</h4>
    <input type="file" id="upload" accept="image/*" multiple />
    <br>
    <label for="quality">压缩比率:(比率越大压缩越大,图片质量越低)</label>
    <input type="range" id="quality" min="0" max="0.9" step="0.1" required value="0.5"/>
    <br>
    <button id="compress">压缩图片</button>
    <br>
    <progress id="progress" value="0" max="100" style="display: none;"></progress>
    <br />
    <span id="progressText"></span>
    <br>
    <div id="outputContainer"></div>
    <br>
    <button id="download" style="display: none;">下载已压缩图片</button>

JavaScript 部分:

import ImageMagicAdapter from 'image-magic-adapter';
let ImageCompressorCls = ImageMagicAdapter.ImageCompressorCls;

const imageCompressor = new ImageCompressorCls(); // 默认压缩质量

 // -----------------------------------------图片压缩-----------------------------------------
        document.getElementById('quality').addEventListener('input', () => {
            const quality = parseFloat(document.getElementById('quality').value);
            imageCompressor.quality = 1 - quality; // 更新压缩质量
            console.log('更新后的压缩质量:', imageCompressor.quality);
        });
        document.getElementById('compress').addEventListener('click', async () => {
            const fileInput = document.getElementById('upload');
            if (!fileInput.files.length) {
                alert('请上传图片');
                return;
            }

            const files = Array.from(fileInput.files);
            const progress = document.getElementById('progress');
            const outputContainer = document.getElementById('outputContainer');
            const downloadButton = document.getElementById('download');
            const progressText = document.getElementById('progressText');

            outputContainer.innerHTML = '';
            downloadButton.style.display = 'none';
            progress.style.display = 'block';
            progress.value = 0;
            progressText.innerText = '';
            // compressImages参数说明:
            //  第一个参数: files:需要压缩的文件数组
            //  第二个参数: callback:压缩完成后的回调函数
            //  第三个参数: 若是压缩png/bmp格式,输出是否保留png/bmp格式,默认为true(建议设置为false)
            // 注意:如果 第三个参数设置true压缩png/bmp格式后的输出的文件为原格式(png/bmp)且压缩效果不佳,就需要依赖设置scaleFactor来调整压缩比例(0-1);如果设置为false,输出为image/jpeg格式且压缩效果更好。
            // 设置caleFactor为0-1,值越大,压缩比例越小,值越小,压缩比例越大(本质是改变图片的尺寸),例: imageCompressor.scaleFactor = 0.5;
            await imageCompressor.compressImages(files, (completed, total) => {
                const outputImg = document.createElement('img');
                outputImg.src = imageCompressor.compressedImages[completed - 1];
                outputContainer.appendChild(outputImg);
                progress.value = (completed / total) * 100;
                progressText.innerText = `已完成文件数: ${completed} / 总文件数: ${total}`;
                if (completed === total) {
                    downloadButton.style.display = 'inline-block';
                }
            }, false);

            downloadButton.onclick = () => {
                if (imageCompressor.compressedImages.length > 0) {
                    imageCompressor.downloadZip(imageCompressor.compressedImages);
                }
            };
        });

图片/PDF格式转换

HTML 部分:

<h4>图片/Pdf格式转换Demo</h4>
    <input type="file" id="upload2" accept="*" multiple />
    <br>
    <button id="imgFormatToPng">转格式</button>

JavaScript 部分:

 // 图片或pdf格式转换方法
        document.getElementById('imgFormatToPng').addEventListener('click', async () => {
            try {
                const fileInput = document.getElementById('upload2');
                if (!fileInput.files.length) {
                    alert('请上传图片');
                    return;
                }
                const files = Array.from(fileInput.files);
                console.log('files==>', files);
                 // 图片转图片格式(支持转['image/jpeg', 'image/png', 'image/webp', 'image/jpg', 'image/bmp']格式)
                // let afterUrl = await imageCompressor.imgFormatFn(files[0], 'image/png', true);

                // png图片转pdf格式
                // let afterUrl = await imageCompressor.imgFormatFn(files[0], 'application/pdf', true);

                // pdf转图片格式(支持转为['image/jpeg', 'image/png']格式)
               let afterUrl = await imageCompressor.imgFormatFn(files[0], 'image/jpeg', true);
                // console.log('afterUrl==>', afterUrl);
            } catch (error) {
                console.log('转换失败:', error);
            }
        })

添加水印

HTML 部分:

<div class="watermarkBox">
        <h4>水印图片Demo</h4>
        <input type="file" id="upload3" accept="image/*" />
        <br>
        <input type="text" id="watermarkText" placeholder="输入水印文字" />
        <br>
        <input type="text" id="fontFamily" placeholder="输入水印字体,例如 'Arial'" value="Arial" />
        <br>
        <input type="number" id="fontSize" placeholder="字体大小" value="30" />
        <br>
        <input type="number" id="rotation" placeholder="旋转角度 (°)" value="0" />
        <br>
        <label>
            <input type="checkbox" id="repeat" />
            水印重复铺满
        </label>
        <br>
        <input type="color" id="color" value="#ffffff" />
        <br>
        <input type="number" id="opacity" placeholder="透明度 (0-1)" value="0.5" step="0.1" min="0" max="1" />
        <br>
        <input type="file" id="watermarkImage" accept="image/*" placeholder="图片水印"/>
        <br>
        <button id="applyWatermark">添加水印</button>
        <br>
        <hr>
        <div id="outputContainer3"></div>
        

        <hr>
        <h4>图片尺寸修改工具Demo</h4>
        <input type="file" id="file-upload" accept="image/*">
        <br><br>
        <img id="image-preview" alt="预览图片" />
        <br><br>
        <label for="width">宽度:</label>
        <input type="number" id="width" placeholder="宽度 (px)">
        <label for="height">高度:</label>
        <input type="number" id="height" placeholder="高度 (px)">
        <br><br>
        <button id="resize-button">修改尺寸</button>
        <button id="download-button">下载图片</button>
    </div>

JavaScript 部分:

// -----------------------------------------添加水印-----------------------------------------
        document.getElementById('applyWatermark').addEventListener('click', () => {
            const fileInput = document.getElementById('upload3');
            const watermarkText = document.getElementById('watermarkText').value;
            const fontFamily = document.getElementById('fontFamily').value;
            const fontSize = parseInt(document.getElementById('fontSize').value);
            const rotation = parseFloat(document.getElementById('rotation').value);
            const shouldRepeat = document.getElementById('repeat').checked;
            const color = document.getElementById('color').value;
            const opacity = parseFloat(document.getElementById('opacity').value);
            const watermarkImageFile = document.getElementById('watermarkImage').files[0]; // 获取水印图片

            if (!fileInput.files.length) {
                alert('请上传图片');
                return;
            }
            const file = fileInput.files[0];
             // 调用通用水印方法(文字水印和图片水印不共存 如果设置了watermarkText那么watermarkImageFile 将失效)
            imageCompressor.applyWatermarkToImage(file, {
                // 文字水印 
                watermarkText,
                // 文字水印字体
                fontFamily,
                //  文字水印尺寸(px)
                fontSize,
                // 水印旋转角度
                rotation,
                // 水印是否重复
                shouldRepeat,
                // 水印颜色
                color,
                // 水印透明度
                opacity,
                // 图片水印(如果有watermarkText将不生效,不共存)
                watermarkImageFile,
                // 水印位置,可选值 top-left center top bottom left right top-right bottom-left bottom-right
                watermarkPosition: 'top-left'
            }, (baseData) => {
                // 显示结果
                const outputContainer = document.getElementById('outputContainer3');
                outputContainer.innerHTML = '';
                const outputImg = document.createElement('img');
                outputImg.src = baseData;
                outputContainer.appendChild(outputImg);
                // 下载水印图片
                imageCompressor.downloadFn(baseData, 'watermarkedImage.png')
            }, err => {
                alert(err);
            });
        });

修改图片尺寸

HTML 部分:

<input type="file" id="file-upload" accept="image/*">
<img id="image-preview" alt="预览图片" />
 <label for="width">宽度:</label>
<input type="number" id="width" placeholder="宽度 (px)">
<label for="height">高度:</label>
<input type="number" id="height" placeholder="高度 (px)">
<button id="resize-button">修改尺寸</button>
<button id="download-button">下载图片</button>

JavaScript 部分:

import ImageMagicAdapter from 'image-magic-adapter';
let ImageResizerCls = ImageMagicAdapter.ImageResizerCls;

const imageResizer = new ImageResizerCls('file-upload', 'image-preview', 'width', 'height', 'resize-button', 'download-button');

API

ImageCompressorCls

  • compressImages(files, callback):压缩图片。
  • imgFormatFn(file, format, shouldDownload):转换图片或PDF格式。
  • applyWatermarkToImage(file, options, callback, errorCallback):给图片添加水印。
  • downloadFn(dataUrl, filename):下载图片。

ImageResizerCls

  • 构造函数接收五个参数,分别是文件上传控件ID、图片预览控件ID、宽度输入框ID、高度输入框ID和尺寸修改按钮ID。

贡献

欢迎贡献代码、解决问题和提出改进建议。

许可证

MIT

1.0.55

1 year ago

1.0.54

1 year ago

1.0.53

1 year ago

1.0.52

1 year ago

1.0.51

1 year ago

1.0.50

1 year ago

1.0.49

1 year ago

1.0.48

1 year ago

1.0.47

1 year ago

1.0.46

1 year ago

1.0.45

1 year ago

1.0.44

1 year ago

1.0.43

1 year ago

1.0.41

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago