How to use the tinify.key function in tinify

To help you get started, we’ve selected a few tinify examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github HuJiaoHJ / blog / tinify.js View on Github external
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 {
github skyujilong / tinypng-webpack-plugin / src / uploader.js View on Github external
});
                //压缩图片成功
                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);
                }
            }
        }
github cklwblove / vue-cli3-template / build / tinypng.js View on Github external
'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 {
github Croc-ye / tinyhere / libs / util.js View on Github external
return new Promise(async (resolve)=> {
        tinify.key = apiKey;
        tinify.validate(function(err) {
            if (err) {
                console.log('该api-key不是有效值');
                resolve(false);
            }
        });
        let count = 500;
        Object.defineProperty(tinify, 'compressionCount', {
            get: ()=> {
                return count;
            },
            set: newValue => {
                count = newValue;
                resolve(true);
            },
            enumerable : true,
github uber / react-vis / www / generate / blogpost.js View on Github external
const path = require('path')
const fs = require('fs')
const jsToYaml = require('json-to-pretty-yaml')
const mkdirp = require('mkdirp')
const slugify = require('@sindresorhus/slugify')
const inquirer = require('inquirer')
const prettier = require('prettier')
const tinify = require('tinify')
require('dotenv').config({
  path: path.join(__dirname, '.env'),
})

const fromRoot = (...p) => path.join(__dirname, '..', ...p)

tinify.key = process.env.TINY_PNG_API_KEY

const padLeft0 = n => n.toString().padStart(2, '0')
const formatDate = d =>
  `${d.getFullYear()}-${padLeft0(d.getMonth() + 1)}-${padLeft0(d.getDate())}`

const listify = a =>
  a && a.trim().length
    ? a
        .split(',')
        .map(s => s.trim())
        .filter(Boolean)
    : null

async function generateBlogPost() {
  const {title, description, categories, keywords} = await inquirer.prompt([
    {
github odrick / free-tex-packer / electron / main.js View on Github external
ipcMain.on('tinify', (e, data) => {
    tinify.key = data.key;
    tinify.fromBuffer(Buffer.from(data.imageData, 'base64')).toBuffer((err, res) => {
        if (err) {
            e.sender.send('tinify-complete', {
                success: false,
                uid: data.uid,
                error: err.message
            });
            return;
        }
        
        e.sender.send('tinify-complete', {
            success: true,
            uid: data.uid,
            data: res.toString('base64')
        });
    });
github muwoo / tinypng-upload / src / renderer / assets / js / operate.js View on Github external
getCompressFile (path) {
    tinify.key = this.options.apiKey
    return new Promise((resolve, reject) => {
      let sourceData = fs.readFileSync(path)
      tinify.fromBuffer(sourceData).toBuffer((err, resultData) => {
        if (err instanceof tinify.AccountError) {
          reject(err)
          return new Notification('compress filed', {
            body: 'Verify your API key and account limit.'
          })
        } else if (err instanceof tinify.ServerError) {
          reject(err)
          return new Notification('compress filed', {
            body: 'Temporary issue with the Tinify API.'
          })
        } else if (err instanceof tinify.ConnectionError) {
          reject(err)
          return new Notification('compress filed', {
github skyujilong / tinypng-webpack-plugin / src / compression.js View on Github external
(function tinifyCompress() {
            tinify.key = __keys[0];
            tinify.fromBuffer(fileInfo.data).toBuffer(function(err, resultData) {
                if (err instanceof tinify.AccountError && __keys.length > 1) {
                    //更换秘钥
                    __keys.splice(0, 1);
                    tinifyCompress();
                } else if (err instanceof tinify.ServerError && __serverErrorRetry -- > 0) {
                    tinifyCompress();
                } else if(err){
                    reject(err);
                } else {
                    resolve({
                        dir: fileInfo.dir,
                        compressionData: resultData
                    });
                }
            });

tinify

Node.js client for the Tinify API. Tinify compresses your images intelligently. Read more at https://tinify.com.

MIT
Latest version published 2 years ago

Package Health Score

50 / 100
Full package analysis