webp-light-converter 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -0
- package/index.js +134 -0
- package/package.json +57 -0
- package/test/example.png +0 -0
- package/test/test.js +68 -0
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# WebP Light Converter
|
|
2
|
+
|
|
3
|
+
Uma biblioteca leve para converter imagens para formato WebP com compressão sem perdas.
|
|
4
|
+
|
|
5
|
+
## 🚀 Instalação
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install webp-light-converter
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## 📋 Características
|
|
12
|
+
|
|
13
|
+
- ✅ Conversão sem perdas (lossless)
|
|
14
|
+
- ✅ Máxima qualidade preservada
|
|
15
|
+
- ✅ Suporte a múltiplos formatos de entrada
|
|
16
|
+
- ✅ Conversão em lote de diretórios
|
|
17
|
+
- ✅ Preservação de metadados da imagem
|
|
18
|
+
- ✅ API simples e direta
|
|
19
|
+
- ⚡ Alta performance com Sharp
|
|
20
|
+
|
|
21
|
+
## 📁 Formatos Suportados
|
|
22
|
+
|
|
23
|
+
**Entrada:** JPG, JPEG, PNG, BMP, TIFF, GIF
|
|
24
|
+
**Saída:** WebP
|
|
25
|
+
|
|
26
|
+
## 📚 Uso
|
|
27
|
+
|
|
28
|
+
### Importando a biblioteca
|
|
29
|
+
|
|
30
|
+
```javascript
|
|
31
|
+
const { convertFile, convertPath } = require('webp-light-converter');
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Converter um arquivo único
|
|
35
|
+
|
|
36
|
+
```javascript
|
|
37
|
+
const { convertFile } = require('webp-light-converter');
|
|
38
|
+
const fs = require('fs');
|
|
39
|
+
|
|
40
|
+
async function exemplo() {
|
|
41
|
+
try {
|
|
42
|
+
// Converte uma imagem para buffer WebP
|
|
43
|
+
const webpBuffer = await convertFile('./input/image.jpg');
|
|
44
|
+
|
|
45
|
+
// Salva o buffer em um arquivo
|
|
46
|
+
fs.writeFileSync('./output/image.webp', webpBuffer);
|
|
47
|
+
|
|
48
|
+
console.log('Conversão concluída!');
|
|
49
|
+
} catch (error) {
|
|
50
|
+
console.error('Erro na conversão:', error.message);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
exemplo();
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Converter um diretório inteiro
|
|
58
|
+
|
|
59
|
+
```javascript
|
|
60
|
+
const { convertPath } = require('webp-light-converter');
|
|
61
|
+
|
|
62
|
+
async function exemploLote() {
|
|
63
|
+
try {
|
|
64
|
+
const resultados = await convertPath('./input', './output');
|
|
65
|
+
|
|
66
|
+
resultados.forEach(resultado => {
|
|
67
|
+
if (resultado.success) {
|
|
68
|
+
console.log(`✅ ${resultado.input} → ${resultado.output}`);
|
|
69
|
+
} else {
|
|
70
|
+
console.log(`❌ ${resultado.input}: ${resultado.error}`);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
} catch (error) {
|
|
74
|
+
console.error('Erro na conversão:', error.message);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
exemploLote();
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## 🔧 API
|
|
82
|
+
|
|
83
|
+
### `convertFile(inputPath)`
|
|
84
|
+
|
|
85
|
+
Converte um único arquivo de imagem para formato WebP.
|
|
86
|
+
|
|
87
|
+
- **inputPath** `{string}` - Caminho para o arquivo de entrada
|
|
88
|
+
- **Retorna** `{Promise<Buffer>}` - Buffer contendo a imagem WebP
|
|
89
|
+
- **Lança** `{Error}` - Se o arquivo não for encontrado
|
|
90
|
+
|
|
91
|
+
### `convertPath(inputDir, outputDir)`
|
|
92
|
+
|
|
93
|
+
Converte todas as imagens de um diretório para formato WebP.
|
|
94
|
+
|
|
95
|
+
- **inputDir** `{string}` - Diretório de entrada
|
|
96
|
+
- **outputDir** `{string}` - Diretório de saída
|
|
97
|
+
- **Retorna** `{Promise<Array>}` - Array com resultados da conversão
|
|
98
|
+
- **Lança** `{Error}` - Se o diretório de entrada não existir
|
|
99
|
+
|
|
100
|
+
#### Formato do resultado:
|
|
101
|
+
|
|
102
|
+
```javascript
|
|
103
|
+
[
|
|
104
|
+
{
|
|
105
|
+
success: true,
|
|
106
|
+
input: 'image.jpg',
|
|
107
|
+
output: 'image.webp',
|
|
108
|
+
path: '/path/to/output/image.webp'
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
success: false,
|
|
112
|
+
input: 'corrupted.png',
|
|
113
|
+
error: 'Mensagem de erro'
|
|
114
|
+
}
|
|
115
|
+
]
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## ⚙️ Configurações
|
|
119
|
+
|
|
120
|
+
A biblioteca usa configurações otimizadas para máxima qualidade:
|
|
121
|
+
|
|
122
|
+
- **Lossless**: `true` (sem perdas)
|
|
123
|
+
- **Quality**: `100` (máxima qualidade)
|
|
124
|
+
- **Effort**: `6` (máximo esforço de compressão)
|
|
125
|
+
- **Metadados**: Preservados
|
|
126
|
+
|
|
127
|
+
## 📄 Licença
|
|
128
|
+
|
|
129
|
+
MIT © [Jonatan966](https://ojonatan.dev)
|
|
130
|
+
|
|
131
|
+
## 🤝 Contribuindo
|
|
132
|
+
|
|
133
|
+
1. Faça um fork do projeto
|
|
134
|
+
2. Crie sua feature branch (`git checkout -b feature/nova-funcionalidade`)
|
|
135
|
+
3. Commit suas mudanças (`git commit -am 'Adiciona nova funcionalidade'`)
|
|
136
|
+
4. Push para a branch (`git push origin feature/nova-funcionalidade`)
|
|
137
|
+
5. Abra um Pull Request
|
|
138
|
+
|
|
139
|
+
## 🐛 Reportar Problemas
|
|
140
|
+
|
|
141
|
+
[Abra uma issue](https://github.com/Jonatan966/webp-light-converter/issues) no GitHub.
|
package/index.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
const sharp = require("sharp");
|
|
2
|
+
const fs = require("fs");
|
|
3
|
+
const path = require("path");
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Converte um único arquivo de imagem para formato WebP com compressão sem perdas.
|
|
7
|
+
*
|
|
8
|
+
* @param {string} inputPath - Caminho absoluto ou relativo para o arquivo de imagem de entrada
|
|
9
|
+
* @returns {Promise<Buffer>} Buffer contendo a imagem convertida em formato WebP
|
|
10
|
+
* @throws {Error} Lança erro se o arquivo de entrada não for encontrado
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // Converter uma imagem JPG para WebP
|
|
14
|
+
* const webpBuffer = await convertFile('./images/photo.jpg');
|
|
15
|
+
* fs.writeFileSync('./output/photo.webp', webpBuffer);
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* // Tratamento de erro
|
|
19
|
+
* try {
|
|
20
|
+
* const buffer = await convertFile('./nonexistent.png');
|
|
21
|
+
* } catch (error) {
|
|
22
|
+
* console.error('Arquivo não encontrado:', error.message);
|
|
23
|
+
* }
|
|
24
|
+
*/
|
|
25
|
+
async function convertFile(inputPath) {
|
|
26
|
+
if (!fs.existsSync(inputPath)) {
|
|
27
|
+
throw new Error(`Arquivo de origem não encontrado: ${inputPath}`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return await sharp(inputPath)
|
|
31
|
+
.webp({
|
|
32
|
+
lossless: true,
|
|
33
|
+
quality: 100,
|
|
34
|
+
effort: 6,
|
|
35
|
+
})
|
|
36
|
+
.keepMetadata()
|
|
37
|
+
.toBuffer();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Converte todas as imagens suportadas de um diretório para formato WebP.
|
|
42
|
+
* Cria o diretório de saída automaticamente se não existir.
|
|
43
|
+
*
|
|
44
|
+
* @param {string} inputDir - Caminho para o diretório contendo as imagens de entrada
|
|
45
|
+
* @param {string} outputDir - Caminho para o diretório onde as imagens WebP serão salvas
|
|
46
|
+
* @returns {Promise<Array<Object>>} Array com resultados da conversão de cada imagem
|
|
47
|
+
* @throws {Error} Lança erro se o diretório de entrada não existir
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* // Converter todas as imagens de uma pasta
|
|
51
|
+
* const results = await convertPath('./input', './output');
|
|
52
|
+
* console.log(`${results.filter(r => r.success).length} imagens convertidas`);
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* // Verificar resultados individuais
|
|
56
|
+
* const results = await convertPath('./photos', './webp-photos');
|
|
57
|
+
* results.forEach(result => {
|
|
58
|
+
* if (result.success) {
|
|
59
|
+
* console.log(`✅ ${result.input} → ${result.output}`);
|
|
60
|
+
* } else {
|
|
61
|
+
* console.log(`❌ Erro em ${result.input}: ${result.error}`);
|
|
62
|
+
* }
|
|
63
|
+
* });
|
|
64
|
+
*
|
|
65
|
+
* @description
|
|
66
|
+
* Formatos suportados: .jpg, .jpeg, .png, .bmp, .tiff, .gif
|
|
67
|
+
*
|
|
68
|
+
* Estrutura do resultado:
|
|
69
|
+
* {
|
|
70
|
+
* success: boolean, // Se a conversão foi bem-sucedida
|
|
71
|
+
* input: string, // Nome do arquivo original
|
|
72
|
+
* output?: string, // Nome do arquivo WebP gerado (se success=true)
|
|
73
|
+
* path?: string, // Caminho completo do arquivo gerado (se success=true)
|
|
74
|
+
* error?: string // Mensagem de erro (se success=false)
|
|
75
|
+
* }
|
|
76
|
+
*/
|
|
77
|
+
async function convertPath(inputDir, outputDir) {
|
|
78
|
+
if (!fs.existsSync(inputDir)) {
|
|
79
|
+
throw new Error(`Pasta de origem não encontrada: ${inputDir}`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (!fs.existsSync(outputDir)) {
|
|
83
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const supportedExtensions = [
|
|
87
|
+
".jpg",
|
|
88
|
+
".jpeg",
|
|
89
|
+
".png",
|
|
90
|
+
".bmp",
|
|
91
|
+
".tiff",
|
|
92
|
+
".gif",
|
|
93
|
+
];
|
|
94
|
+
|
|
95
|
+
const files = fs.readdirSync(inputDir);
|
|
96
|
+
|
|
97
|
+
const imageFiles = files.filter((file) => {
|
|
98
|
+
const ext = path.extname(file).toLowerCase();
|
|
99
|
+
return supportedExtensions.includes(ext);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const results = [];
|
|
103
|
+
|
|
104
|
+
for (const imageFile of imageFiles) {
|
|
105
|
+
try {
|
|
106
|
+
const inputPath = path.join(inputDir, imageFile);
|
|
107
|
+
const outputFileName = `${path.parse(imageFile).name}.webp`;
|
|
108
|
+
const outputPath = path.join(outputDir, outputFileName);
|
|
109
|
+
|
|
110
|
+
const webpBuffer = await convertFile(inputPath);
|
|
111
|
+
fs.writeFileSync(outputPath, webpBuffer);
|
|
112
|
+
|
|
113
|
+
results.push({
|
|
114
|
+
success: true,
|
|
115
|
+
input: imageFile,
|
|
116
|
+
output: outputFileName,
|
|
117
|
+
path: outputPath,
|
|
118
|
+
});
|
|
119
|
+
} catch (error) {
|
|
120
|
+
results.push({
|
|
121
|
+
success: false,
|
|
122
|
+
input: imageFile,
|
|
123
|
+
error: error.message,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return results;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = {
|
|
132
|
+
convertFile,
|
|
133
|
+
convertPath,
|
|
134
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "webp-light-converter",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A lightweight library for converting images to WebP format with lossless compression",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/Jonatan966/webp-light-converter.git"
|
|
8
|
+
},
|
|
9
|
+
"bugs": {
|
|
10
|
+
"url": "https://github.com/Jonatan966/webp-light-converter/issues"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/Jonatan966/webp-light-converter#readme",
|
|
13
|
+
"main": "index.js",
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "node test/test.js"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"webp",
|
|
19
|
+
"image",
|
|
20
|
+
"converter",
|
|
21
|
+
"conversion",
|
|
22
|
+
"lossless",
|
|
23
|
+
"compression",
|
|
24
|
+
"optimization",
|
|
25
|
+
"sharp",
|
|
26
|
+
"batch",
|
|
27
|
+
"jpg",
|
|
28
|
+
"jpeg",
|
|
29
|
+
"png",
|
|
30
|
+
"bmp",
|
|
31
|
+
"tiff",
|
|
32
|
+
"gif",
|
|
33
|
+
"lightweight",
|
|
34
|
+
"image-processing",
|
|
35
|
+
"performance",
|
|
36
|
+
"nodejs"
|
|
37
|
+
],
|
|
38
|
+
"author": "Jonatan966",
|
|
39
|
+
"maintainers": [
|
|
40
|
+
{
|
|
41
|
+
"name": "Jonatan",
|
|
42
|
+
"email": "jonatanfrederico@gmail.com",
|
|
43
|
+
"url": "https://ojonatan.dev"
|
|
44
|
+
}
|
|
45
|
+
],
|
|
46
|
+
"contributors": [
|
|
47
|
+
{
|
|
48
|
+
"name": "Jonatan",
|
|
49
|
+
"email": "jonatanfrederico@gmail.com",
|
|
50
|
+
"url": "https://ojonatan.dev"
|
|
51
|
+
}
|
|
52
|
+
],
|
|
53
|
+
"license": "MIT",
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"sharp": "^0.34.5"
|
|
56
|
+
}
|
|
57
|
+
}
|
package/test/example.png
ADDED
|
Binary file
|
package/test/test.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const { convertFile, convertPath } = require('../index.js');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
|
|
5
|
+
async function runTests() {
|
|
6
|
+
console.log('🧪 Iniciando testes da WebP Light Converter...\n');
|
|
7
|
+
|
|
8
|
+
try {
|
|
9
|
+
// Teste 1: Conversão de arquivo único
|
|
10
|
+
console.log('📋 Teste 1: Conversão de arquivo único');
|
|
11
|
+
console.log('Convertendo test/example.png...');
|
|
12
|
+
|
|
13
|
+
const webpBuffer = await convertFile('./test/example.png');
|
|
14
|
+
|
|
15
|
+
// Criar pasta de output se não existir
|
|
16
|
+
if (!fs.existsSync('./output')) {
|
|
17
|
+
fs.mkdirSync('./output');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
fs.writeFileSync('./output/example.webp', webpBuffer);
|
|
21
|
+
|
|
22
|
+
const stats = fs.statSync('./output/example.webp');
|
|
23
|
+
console.log(`✅ Arquivo convertido com sucesso!`);
|
|
24
|
+
console.log(` Tamanho: ${(stats.size / 1024).toFixed(2)} KB`);
|
|
25
|
+
console.log(` Localização: ./output/example.webp\n`);
|
|
26
|
+
|
|
27
|
+
// Teste 2: Conversão de diretório
|
|
28
|
+
console.log('📋 Teste 2: Conversão de diretório');
|
|
29
|
+
console.log('Convertendo pasta test/ para output/batch/...');
|
|
30
|
+
|
|
31
|
+
const results = await convertPath('./test', './output/batch');
|
|
32
|
+
|
|
33
|
+
console.log('\n📊 Resultados da conversão em lote:');
|
|
34
|
+
results.forEach((result, index) => {
|
|
35
|
+
if (result.success) {
|
|
36
|
+
const stats = fs.statSync(result.path);
|
|
37
|
+
console.log(` ${index + 1}. ✅ ${result.input} → ${result.output}`);
|
|
38
|
+
console.log(` Tamanho: ${(stats.size / 1024).toFixed(2)} KB`);
|
|
39
|
+
} else {
|
|
40
|
+
console.log(` ${index + 1}. ❌ ${result.input}: ${result.error}`);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const successful = results.filter(r => r.success).length;
|
|
45
|
+
console.log(`\n🎉 Testes concluídos: ${successful}/${results.length} conversões bem-sucedidas`);
|
|
46
|
+
|
|
47
|
+
// Teste 3: Tratamento de erro
|
|
48
|
+
console.log('\n📋 Teste 3: Tratamento de erro (arquivo inexistente)');
|
|
49
|
+
try {
|
|
50
|
+
await convertFile('./inexistente.jpg');
|
|
51
|
+
console.log('❌ Erro: deveria ter lançado exceção');
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.log(`✅ Erro capturado corretamente: ${error.message}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
console.log('\n🎯 Todos os testes foram executados com sucesso!');
|
|
57
|
+
console.log('\n📁 Arquivos gerados:');
|
|
58
|
+
console.log(' - ./output/example.webp');
|
|
59
|
+
console.log(' - ./output/batch/example.webp');
|
|
60
|
+
|
|
61
|
+
} catch (error) {
|
|
62
|
+
console.error('❌ Erro durante os testes:', error.message);
|
|
63
|
+
process.exit(1);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Executar testes
|
|
68
|
+
runTests();
|