• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript sharp类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中sharp的典型用法代码示例。如果您正苦于以下问题:TypeScript sharp类的具体用法?TypeScript sharp怎么用?TypeScript sharp使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了sharp类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: processImage

	public processImage (req, res, next) {
		const _finish = (data) => {
			res.set({"Content-Type": res.locals.image_headers["content-type"]})
			.send(data);
			next();
		};
		if (!res.locals.image_size) {
			_finish(res.locals.image_body);
		}
		else if (res.locals.image_iscrop) {
			sharp(res.locals.image_body)
			.resize(res.locals.image_size, res.locals.image_size)
			.toBuffer()
			.then(_finish)
			.catch(next);
		}
		else {
			sharp(res.locals.image_body)
			.resize(res.locals.image_size, null)
			.withoutEnlargement(true)
			.toBuffer()
			.then(_finish)
			.catch(next);
		}
	}
开发者ID:smrchy,项目名称:docker,代码行数:25,代码来源:mw.ts


示例2: saveFile

    async saveFile(blog: Blog, file: Express.Multer.File): Promise<string> {
        const extStart = file.originalname.lastIndexOf('.')
        const name = file.originalname.substr(0, extStart)

        // If the file is an image create thumbnails + convert to webp
        if (file.mimetype.includes('image')) {
            for (const height of IMAGE_SIZES) {
                await sharp(file.path)
                    .resize(null, height)
                    .webp({alphaQuality: 0})
                    .toFile(j(this.getDir(blog), name + '.h' + height + '.webp'))
            }

            // Convert to webp
            let img = sharp(file.path)
                .webp({alphaQuality: 0})

            // if image is bigger than original size resize it
            if ((await img.stats()).channels.reduce((v, s) => (v > s.maxY) ? v : s.maxY, 0) > IMAGE_MAX_SIZE) {
                img = img.resize(null, IMAGE_MAX_SIZE)
            }

            await img.toFile(j(this.getDir(blog), name + '.webp'))

            // Delete original image
            await unlinker(file.path)

            return name + '.webp'
        }

        // Not an image, just move to right location
        await renamer(file.path, j(this.getDir(blog), file.originalname))
        return file.originalname
    }
开发者ID:m1cr0man,项目名称:m1cr0blog,代码行数:34,代码来源:repository.ts


示例3: join

    const uploadPromises = THUMBNAILSIZES.map(async thumbDef => {

      const thumbFileName = `thumb_${fileName}_${thumbDef.name}.${contentType.substring(contentType.indexOf('/') + 1)}`;
      const thumbFilePath = join(workingDir, thumbFileName);

      const fileTransform = sharp(tmpFilePath);

      if (object.contentType === 'image/jpeg') {
        fileTransform.jpeg({ quality: thumbDef.quality });
      }
      if (object.contentType === 'image/png') {
        fileTransform.png({ quality: thumbDef.quality });
      }

      if (thumbDef.width && thumbDef.height) {
        console.log(thumbDef);
        fileTransform.resize({ width: thumbDef.width, height: thumbDef.height });
      } else if (!thumbDef.width && thumbDef.height) {
        fileTransform.resize({ height: thumbDef.height });
      } else {
        fileTransform.resize(thumbDef.width);
      }

      await fileTransform.toFile(thumbFilePath);

      return bucket.upload(thumbFilePath, {
        destination: join(bucketDir, thumbFileName),
        metadata: metadata
      });
    });
开发者ID:Meistercoach83,项目名称:sfw,代码行数:30,代码来源:generate-thumbnails.ts


示例4: getClippedComponentScreenshot

function* getClippedComponentScreenshot(req: express.Request, res: express.Response, next) {
  const state = yield select();
  const { componentId, previewName } = req.params;
  const { uri } = (yield call(getComponentsScreenshotFromReq, req)) || { uri: null };

  const { maxWidth, maxHeight } = req.query;

  if (!uri) {
    return next();
  }

  const screenshot = getComponentScreenshot(componentId, previewName, state);

  if (!screenshot) {
    return next();
  }

  const box = {
    left: screenshot.clip.left,
    top: screenshot.clip.top,
    width: screenshot.clip.right - screenshot.clip.left,
    height: screenshot.clip.bottom - screenshot.clip.top,
  };

  let cw = box.width;
  let ch = box.height;

  let stream = sharp(uri).extract(box);

  if (maxWidth && cw > Number(maxWidth)) {
    const scale = Number(maxWidth) / cw; // 100 / 200 = 0.5
    cw *= scale;
    ch *= scale;
  }

  if (maxHeight && ch > Number(maxHeight)) {
    const scale = Number(maxHeight) / ch; // 100 / 200 = 0.5
    cw *= scale;
    ch *= scale;
  }

  if (cw !== box.width) {
    stream = stream.resize(Math.round(cw), Math.round(ch));
  }

  const buffer = yield call(stream.toBuffer.bind(stream));

  res.setHeader("Content-Length", buffer.length);
  res.setHeader("Content-Type", "image/png");
  res.setHeader("Accept-Ranges", "bytes");
  res.setHeader("Connection", "keep-alive");

  res.end(buffer);

  // stream.pipe(res);
}
开发者ID:cryptobuks,项目名称:tandem,代码行数:56,代码来源:api.ts


示例5: processImage

async function processImage (
  physicalFile: { path: string },
  destination: string,
  newSize: { width: number, height: number }
) {
  await sharp(physicalFile.path)
    .resize(newSize.width, newSize.height)
    .toFile(destination)

  await unlinkPromise(physicalFile.path)
}
开发者ID:jiang263,项目名称:PeerTube,代码行数:11,代码来源:image-utils.ts


示例6: registerBridge

registerBridge("fly.Image()", function imageConstructor(
  rt: Runtime,
  bridge: Bridge,
  data?: ivm.Reference<Buffer>,
  create?: any
) {
  try {
    if (data && !(data instanceof ArrayBuffer)) {
      throw new Error("image data must be an ArrayBuffer")
    }
    const opts: any = {}
    if (create) {
      if (typeof create.background === "string") {
        // create.background = color.parse(create.background)
      }
      opts.create = create
    }
    const image = sharp(data && Buffer.from(data), opts)
    const ref = new ivm.Reference(image)
    return Promise.resolve(ref)
  } catch (e) {
    return Promise.reject(e)
  }
})
开发者ID:dianpeng,项目名称:fly,代码行数:24,代码来源:image.ts


示例7: save

async function save(path: string, name: string, type: string, hash: string, size: number, metadata: any): Promise<IDriveFile> {
	let thumbnail: Buffer;

	if (['image/jpeg', 'image/png', 'image/webp'].includes(type)) {
		thumbnail = await sharp(path)
			.resize(300)
			.jpeg({
				quality: 50,
				progressive: true
			})
			.toBuffer();
	}

	if (config.drive && config.drive.storage == 'minio') {
		const minio = new Minio.Client(config.drive.config);
		const key = `${config.drive.prefix}/${uuid.v4()}/${name}`;
		const thumbnailKey = `${config.drive.prefix}/${uuid.v4()}/${name}.thumbnail.jpg`;

		const baseUrl = config.drive.baseUrl
			|| `${ config.drive.config.secure ? 'https' : 'http' }://${ config.drive.config.endPoint }${ config.drive.config.port ? ':' + config.drive.config.port : '' }/${ config.drive.bucket }`;

		await minio.putObject(config.drive.bucket, key, fs.createReadStream(path), size, {
			'Content-Type': type,
			'Cache-Control': 'max-age=31536000, immutable'
		});

		if (thumbnail) {
			await minio.putObject(config.drive.bucket, thumbnailKey, thumbnail, size, {
				'Content-Type': 'image/jpeg',
				'Cache-Control': 'max-age=31536000, immutable'
			});
		}

		Object.assign(metadata, {
			withoutChunks: true,
			storage: 'minio',
			storageProps: {
				key: key,
				thumbnailKey: thumbnailKey
			},
			url: `${ baseUrl }/${ key }`,
			thumbnailUrl: thumbnail ? `${ baseUrl }/${ thumbnailKey }` : null
		});

		const file = await DriveFile.insert({
			length: size,
			uploadDate: new Date(),
			md5: hash,
			filename: name,
			metadata: metadata,
			contentType: type
		});

		return file;
	} else {
		// Get MongoDB GridFS bucket
		const bucket = await getDriveFileBucket();

		const file = await new Promise<IDriveFile>((resolve, reject) => {
			const writeStream = bucket.openUploadStream(name, {
				contentType: type,
				metadata
			});

			writeStream.once('finish', resolve);
			writeStream.on('error', reject);

			fs.createReadStream(path).pipe(writeStream);
		});

		if (thumbnail) {
			const thumbnailBucket = await getDriveFileThumbnailBucket();

			await new Promise<IDriveFile>((resolve, reject) => {
				const writeStream = thumbnailBucket.openUploadStream(name, {
					contentType: 'image/jpeg',
					metadata: {
						originalId: file._id
					}
				});

				writeStream.once('finish', resolve);
				writeStream.on('error', reject);
				writeStream.end(thumbnail);
			});
		}

		return file;
	}
}
开发者ID:ha-dai,项目名称:Misskey,代码行数:90,代码来源:add-file.ts


示例8: function


//.........这里部分代码省略.........
		if (usage + size > driveCapacity) {
			if (isLocalUser(user)) {
				throw 'no-free-space';
			} else {
				// (アバターまたはバナーを含まず)最も古いファイルを削除する
				deleteOldFile(user);
			}
		}
	}
	//#endregion

	const fetchFolder = async () => {
		if (!folderId) {
			return null;
		}

		const driveFolder = await DriveFolder.findOne({
			_id: folderId,
			userId: user._id
		});

		if (driveFolder == null) throw 'folder-not-found';

		return driveFolder;
	};

	const properties: {[key: string]: any} = {};

	let propPromises: Array<Promise<void>> = [];

	const isImage = ['image/jpeg', 'image/gif', 'image/png', 'image/webp'].includes(mime);

	if (isImage) {
		const img = sharp(path);

		// Calc width and height
		const calcWh = async () => {
			log('calculate image width and height...');

			// Calculate width and height
			const meta = await img.metadata();

			log(`image width and height is calculated: ${meta.width}, ${meta.height}`);

			properties['width'] = meta.width;
			properties['height'] = meta.height;
		};

		// Calc average color
		const calcAvg = async () => {
			log('calculate average color...');

			try {
				const info = await (img as any).stats();

				const r = Math.round(info.channels[0].mean);
				const g = Math.round(info.channels[1].mean);
				const b = Math.round(info.channels[2].mean);

				log(`average color is calculated: ${r}, ${g}, ${b}`);

				const value = info.isOpaque ? [r, g, b] : [r, g, b, 255];

				properties['avgColor'] = value;
			} catch (e) { }
		};
开发者ID:ha-dai,项目名称:Misskey,代码行数:67,代码来源:add-file.ts


示例9: Buffer

import * as sharp from "sharp";
import { createReadStream, createWriteStream } from "fs";

// Test samples taken from the official documentation

const input: Buffer = new Buffer(0);
const readableStream: NodeJS.ReadableStream = createReadStream(input);
const writableStream: NodeJS.WritableStream = createWriteStream(input);

sharp(input)
    .extractChannel('green')
    .toFile('input_green.jpg', (err, info) => {
        // info.channels === 1
        // input_green.jpg contains the green channel of the input image
    });

sharp('3-channel-rgb-input.png')
    .bandbool(sharp.bool.and)
    .toFile('1-channel-output.png', (err, info) => {
        // The output will be a single channel image where each pixel `P = R & G & B`.
        // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]`
        // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`.
    });

sharp('input.png')
    .rotate(180)
    .resize(300)
    .flatten()
    .background('#ff6600')
    .overlayWith('overlay.png', { gravity: sharp.gravity.southeast })
    .sharpen()
开发者ID:minodisk,项目名称:DefinitelyTyped,代码行数:31,代码来源:sharp-tests.ts


示例10: transformWrite

  new MongoObservable.Collection<Picture>('pictures') as PicturesCollection<Picture>;

export const PicturesStore = new UploadFS.store.GridFS({
  collection: Pictures.collection,
  name: 'pictures',
  filter: new UploadFS.Filter({
    contentTypes: ['image/*']
  }),
  permissions: new UploadFS.StorePermissions({
    insert: picturesPermissions,
    update: picturesPermissions,
    remove: picturesPermissions
  }),
  transformWrite(from, to) {
    // Resize picture, then crop it to 1:1 aspect ratio, then compress it to 75% from its original quality
    const transform = sharp().resize(800,800).min().crop().toFormat('jpeg', {quality: 75});
    from.pipe(transform).pipe(to);
  }
});

// Gets picture's url by a given selector
Pictures.getPictureUrl = function (selector, platform = "") {
  const prefix = platform === "android" ? "/android_asset/www" :
    platform === "ios" ? "" : "";

  const picture = this.findOne(selector) || {};
  return picture.url || prefix + DEFAULT_PICTURE_URL;
};

function picturesPermissions(userId: string): boolean {
  return Meteor.isServer || !!userId;
开发者ID:DAB0mB,项目名称:ionic2-meteor-messenger,代码行数:31,代码来源:pictures.ts



注:本文中的sharp类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript should类代码示例发布时间:2022-05-28
下一篇:
TypeScript serve-static类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap