Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "tinify in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'tinify' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

.forEach(async (png) => {
    const original = statSync(png).size;

    // TinyPNG
    const image = tinify.fromFile(png);
    await image.toFile(png);
    const optimized = statSync(png).size;

    // AdvPNG
    execSync(`advpng -l -4 ${png}`);
    const recompressed = statSync(png).size

    console.log(`${png} ${original} bytes -> TinyPNG ${optimized} bytes -> AdvPNG ${recompressed}`);

    // stage optimized PNG for inclusion in commit
    execSync(`git add ${png}`);
  });
const tinify = require('tinify');
const apiKey = require('./api_key');
const fs = require('fs');
const path = require('path');
// API Key
tinify.key = apiKey;

// 执行图片压缩任务,返回promise对象
const task = file => {
    const source = tinify.fromFile(file.fromFile);
    source.toFile(file.toFile);
    return source._url;
}
// 通过输入文件夹和输出文件夹,返回一个数组
const fromDir = (inDir, outDir, _files = []) => {
    const files = fs.readdirSync(inDir);
    for (let file of files) {
        const filePath = `${inDir}/${file}`;
        const toFilePath = `${outDir}/${file}`;
        if (fs.statSync(filePath).isDirectory()) {
            fromDir(filePath, toFilePath, _files)
        } else {
});
                //压缩图片成功
                fileInfo.source._value = compressImg;
                // 缓存压缩后的文件
                let filePath = yield writeImg(compressImg, fileMd5);
                appendDict[fileMd5] = filePath;
            } catch (err) {
                if (err instanceof tinify.AccountError) {
                    // Verify your API key and account limit.
                    if (!keys) {
                        //输出文件名 fileInfo.name
                        uploadErrorList.push(fileInfo.name);
                        return;
                    }
                    //tinify key 更换
                    tinify.key = _.first(keys);
                    keys = _.drop(keys);
                    yield upload(fileInfo, reTryCount);
                } else {
                    // Something else went wrong, unrelated to the Tinify API.
                    yield upload(fileInfo, reTryCount - 1);
                }
            }
        }
const task = file => {
    const source = tinify.fromFile(file.fromFile);
    source.toFile(file.toFile);
    return source._url;
}
// 通过输入文件夹和输出文件夹,返回一个数组
fs.readFile(name, function(err, sourceData) {
        if (err) throw err;
        tinify.fromBuffer(sourceData).toBuffer(function(err, resultData) {
          if (err) throw err;
          filePath = path.join(filePath, name);
          const writerStream = fs.createWriteStream(filePath);
          // 标记文件末尾
          writerStream.write(resultData,'binary');
          writerStream.end();
      
          // 处理流事件 --> data, end, and error
          writerStream.on('finish', function() {
            failsList.push(null);
            record(name, true, failsList.length, fullLen);
            if (failsList.length === fullLen) {
                finishcb(failsList, filePath);
            }
          });
let compressImg = yield new Promise((resolve, reject) => {
                    tinify.fromBuffer(fileInfo.source.source()).toBuffer((err, resultData) => {
                        if (err) {
                            reject(err);
                        } else {
                            resolve(resultData);
                        }
                    })
                });
                //压缩图片成功
                fileInfo.source._value = compressImg;
                // 缓存压缩后的文件
                let filePath = yield writeImg(compressImg, fileMd5);
                appendDict[fileMd5] = filePath;
            } catch (err) {
                if (err instanceof tinify.AccountError) {
                    // Verify your API key and account limit.
                    if (!keys) {
                        //输出文件名 fileInfo.name
                        uploadErrorList.push(fileInfo.name);
                        return;
                    }
                    //tinify key 更换
                    tinify.key = _.first(keys);
                    keys = _.drop(keys);
                    yield upload(fileInfo, reTryCount);
                } else {
                    // Something else went wrong, unrelated to the Tinify API.
                    yield upload(fileInfo, reTryCount - 1);
                }
            }
        }
var source = tinifypng.fromFile(input);
                var copyrighted = source.preserve(enginepng.png.command[0]);
                copyrighted.toFile(output); 
              }else if(enginepng.png.command.length === 2){

                var source = tinifypng.fromFile(input);
                var copyrighted = source.preserve(enginepng.png.command[0], enginepng.png.command[1]);
                copyrighted.toFile(output); 
              }else if(enginepng.png.command.length === 3){

                var source = tinifypng.fromFile(input);
                var copyrighted = source.preserve(enginepng.png.command[0], enginepng.png.command[1], enginepng.png.command[2]);
                copyrighted.toFile(output); 
              }         
            }else{
              tinifypng.fromFile(input).toFile(output);
            }
        }          
      }else{
        console.log(colors.red("Don't [png] find ["+enginepng.png.engine+"] engine!"));
      }
    }
//- - - - - - - - - - - - -  - - - - - - - - - - -  
                }); 
              });
            }); 
            //-------------------------------------------------                   
        }else{
            var array;
            if(false != enginejpg.jpg.command){
              if(enginejpg.jpg.command.length === 1){

                var source = tinifyjpeg.fromFile(input);
                var copyrighted = source.preserve(enginejpg.jpg.command[0]);
                copyrighted.toFile(output); 
              }else if(enginejpg.jpg.command.length === 2){

                var source = tinifyjpeg.fromFile(input);
                var copyrighted = source.preserve(enginejpg.jpg.command[0], enginejpg.jpg.command[1]);
                copyrighted.toFile(output); 
              }else if(enginejpg.jpg.command.length === 3){

                var source = tinifyjpeg.fromFile(input);
                var copyrighted = source.preserve(enginejpg.jpg.command[0], enginejpg.jpg.command[1], enginejpg.jpg.command[2]);
                copyrighted.toFile(output); 
              }         
            }else{
              tinifyjpeg.fromFile(input).toFile(output);
            }
        }          
      }else{
        console.log(colors.red("Don't [jpg] find ["+enginejpg.jpg.engine+"] engine!"));
      }
    }
fs.readFile(input, function(err, sourceData) {
              if (err){
                throw err;
              } 
              tinifypng.fromBuffer(sourceData).toBuffer(function(err, resultData) {
                if (err){
                  throw err;
                }
                fs.writeFile(output, resultData, function(err) {
                    if(err) {
                        return console.log(err);
                    }
                    //- - - - - - - - - - - - -  - - - - - - - - - - -
                    //Block statistic
                    //- - - - - - - - - - - - -  - - - - - - - - - - -
                    //Узнаем размер файла после сжатия
                    size_output = getFilesizeInBytes(output);
                        
                    //Находим на сколько процентов удалось сжать файл
                    percent = size_output / size_in;
                    percent = percent * 100;
'use strict';

const path = require('path');
const fs = require('fs');
const tinify = require('tinify');
const config = require('../package.json');
const chalk = require('chalk');
if (config.tinypngkey === '') {
  console.log(
    chalk.red(
      '请在package.json 文件配置tinypng的key,如果没有key,请前往【https://tinypng.com/developers】申请'
    )
  );
  return;
}
tinify.key = config.tinypngkey;
const filePath = './src/assets/img';
const files = fs.readdirSync(filePath);
const reg = /\.(jpg|png)$/;
console.log(chalk.yellow(`上传TinyPNG中...`));

async function compress() {
  for (let file of files) {
    let filePathAll = path.join(filePath, file);
    let stats = fs.statSync(path.join(filePath, file));
    if (!stats.isDirectory() && reg.test(file)) {
      await new Promise((resolve, reject) => {
        fs.readFile(filePathAll, (err, sourceData) => {
          if (err) {
            console.log(chalk.red(`${file} 压缩失败`));
            reject(err);
          } else {

Is your System Free of Underlying Vulnerabilities?
Find Out Now