當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript sharp類代碼示例

本文整理匯總了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;未經允許,請勿轉載。