Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03.1k
1/*!2 Copyright 2013 Lovell Fuller and others.3 SPDX-License-Identifier: Apache-2.04*/5 6import path from 'node:path';7import is from './is.mjs';8import sharp from './sharp.mjs';9 10const formats = new Map([11 ['heic', 'heif'],12 ['heif', 'heif'],13 ['avif', 'avif'],14 ['jpeg', 'jpeg'],15 ['jpg', 'jpeg'],16 ['jpe', 'jpeg'],17 ['tile', 'tile'],18 ['dz', 'tile'],19 ['png', 'png'],20 ['raw', 'raw'],21 ['tiff', 'tiff'],22 ['tif', 'tiff'],23 ['webp', 'webp'],24 ['gif', 'gif'],25 ['jp2', 'jp2'],26 ['jpx', 'jp2'],27 ['j2k', 'jp2'],28 ['j2c', 'jp2'],29 ['jxl', 'jxl']30]);31 32const jp2Regex = /\.(jp[2x]|j2[kc])$/i;33 34const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG');35 36const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours)));37 38/**39 * Write output image data to a file.40 *41 * If an explicit output format is not selected, it will be inferred from the extension,42 * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported.43 * Note that raw pixel data is only supported for buffer output.44 *45 * By default all metadata will be removed, which includes EXIF-based orientation.46 * See {@link #withmetadata withMetadata} for control over this.47 *48 * The caller is responsible for ensuring directory structures and permissions exist.49 *50 * A `Promise` is returned when `callback` is not provided.51 *52 * @example53 * sharp(input)54 * .toFile('output.png', (err, info) => { ... });55 *56 * @example57 * sharp(input)58 * .toFile('output.png')59 * .then(info => { ... })60 * .catch(err => { ... });61 *62 * @param {string} fileOut - the path to write the image data to.63 * @param {Function} [callback] - called on completion with two arguments `(err, info)`.64 * `info` contains the output image `format`, `size` (bytes), `width`, `height`,65 * `channels` and `premultiplied` (indicating if premultiplication was used).66 * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.67 * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region.68 * Animated output will also contain `pageHeight` and `pages`.69 * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.70 * @returns {Promise<Object>} - when no callback is provided71 * @throws {Error} Invalid parameters72 */73function toFile (fileOut, callback) {74 let err;75 if (!is.string(fileOut)) {76 err = new Error('Missing output file path');77 } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) {78 err = new Error('Cannot use same file for input and output');79 } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2.output.file) {80 err = errJp2Save();81 }82 if (err) {83 if (is.fn(callback)) {84 callback(err);85 } else {86 return Promise.reject(err);87 }88 } else {89 this.options.fileOut = fileOut;90 const stack = Error();91 return this._pipeline(callback, stack);92 }93 return this;94}95 96/**97 * Write output to a Buffer.98 * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.99 *100 * Use {@link #toformat toFormat} or one of the format-specific functions such as {@link #jpeg jpeg}, {@link #png png} etc. to set the output format.101 *102 * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.103 *104 * By default all metadata will be removed, which includes EXIF-based orientation.105 * See {@link #withmetadata withMetadata} for control over this.106 *107 * `callback`, if present, gets three arguments `(err, data, info)` where:108 * - `err` is an error, if any.109 * - `data` is the output image data.110 * - `info` contains the output image `format`, `size` (bytes), `width`, `height`,111 * `channels` and `premultiplied` (indicating if premultiplication was used).112 * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`.113 * Animated output will also contain `pageHeight` and `pages`.114 * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text.115 *116 * The underlying `ArrayBuffer` may be marked as non-transferable by some JavaScript runtimes.117 * Use {@link #touint8array toUint8Array} for a guaranteed transferable `ArrayBuffer`.118 *119 * A `Promise` is returned when `callback` is not provided.120 *121 * @example122 * const data = await sharp(input)123 * .png()124 * .toBuffer();125 *126 * @example127 * const { data, info } = await sharp(input)128 * .png()129 * .toBuffer({ resolveWithObject: true });130 *131 * @example132 * const { data, info } = await sharp('my-image.jpg')133 * // output the raw pixels134 * .raw()135 * .toBuffer({ resolveWithObject: true });136 *137 * // create a more type safe way to work with the raw pixel data138 * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer139 * // so `data` and `pixelArray` point to the same memory location140 * const pixelArray = new Uint8ClampedArray(data.buffer);141 *142 * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input143 * const { width, height, channels } = info;144 * await sharp(pixelArray, { raw: { width, height, channels } })145 * .toFile('my-changed-image.jpg');146 *147 * @param {Object} [options]148 * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.149 * @param {Function} [callback]150 * @returns {Promise<Buffer>} - when no callback is provided151 */152function toBuffer (options, callback) {153 if (is.object(options)) {154 this._setBooleanOption('resolveWithObject', options.resolveWithObject);155 } else if (this.options.resolveWithObject) {156 this.options.resolveWithObject = false;157 }158 this.options.fileOut = '';159 const stack = Error();160 return this._pipeline(is.fn(options) ? options : callback, stack);161}162 163/**164 * Write output to a `Uint8Array` backed by a transferable `ArrayBuffer`.165 * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.166 *167 * Use {@link #toformat toFormat} or one of the format-specific functions such as {@link #jpeg jpeg}, {@link #png png} etc. to set the output format.168 *169 * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.170 *171 * By default all metadata will be removed, which includes EXIF-based orientation.172 * See {@link #keepexif keepExif} and similar methods for control over this.173 *174 * Resolves with an `Object` containing:175 * - `data` is the output image as a `Uint8Array` backed by a transferable `ArrayBuffer`.176 * - `info` contains properties relating to the output image such as `width` and `height`.177 *178 * @since v0.35.0179 *180 * @example181 * const { data, info } = await sharp(input).toUint8Array();182 *183 * @example184 * const { data } = await sharp(input)185 * .avif()186 * .toUint8Array();187 * const base64String = data.toBase64();188 *189 * @returns {Promise<{ data: Uint8Array, info: Object }>}190 */191function toUint8Array () {192 this.options.resolveWithObject = true;193 this.options.typedArrayOut = true;194 const stack = Error();195 return this._pipeline(null, stack);196}197 198/**199 * Set output density (DPI) in EXIF metadata.200 *201 * @since 0.35.0202 *203 * @example204 * const data = await sharp(input)205 * .withDensity(96)206 * .toBuffer();207 *208 * @param {number} density Number of pixels per inch (DPI).209 * @returns {Sharp}210 * @throws {Error} Invalid parameters211 */212function withDensity (density) {213 if (is.number(density) && density > 0) {214 this.options.withMetadataDensity = density;215 } else {216 throw is.invalidParameterError('density', 'positive number', density);217 }218 return this.keepExif();219}220 221/**222 * Keep all EXIF metadata from the input image in the output image.223 *224 * EXIF metadata is unsupported for TIFF output.225 *226 * @since 0.33.0227 *228 * @example229 * const outputWithExif = await sharp(inputWithExif)230 * .keepExif()231 * .toBuffer();232 *233 * @returns {Sharp}234 */235function keepExif () {236 this.options.keepMetadata |= 0b00001;237 return this;238}239 240/**241 * Set EXIF metadata in the output image, ignoring any EXIF in the input image.242 *243 * @since 0.33.0244 *245 * @example246 * const dataWithExif = await sharp(input)247 * .withExif({248 * IFD0: {249 * Copyright: 'The National Gallery'250 * },251 * IFD3: {252 * GPSLatitudeRef: 'N',253 * GPSLatitude: '51/1 30/1 3230/100',254 * GPSLongitudeRef: 'W',255 * GPSLongitude: '0/1 7/1 4366/100'256 * }257 * })258 * .toBuffer();259 *260 * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.261 * @returns {Sharp}262 * @throws {Error} Invalid parameters263 */264function withExif (exif) {265 if (is.object(exif)) {266 for (const [ifd, entries] of Object.entries(exif)) {267 if (is.object(entries)) {268 for (const [k, v] of Object.entries(entries)) {269 if (is.string(v)) {270 this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v;271 } else {272 throw is.invalidParameterError(`${ifd}.${k}`, 'string', v);273 }274 }275 } else {276 throw is.invalidParameterError(ifd, 'object', entries);277 }278 }279 } else {280 throw is.invalidParameterError('exif', 'object', exif);281 }282 this.options.withExifMerge = false;283 return this.keepExif();284}285 286/**287 * Update EXIF metadata from the input image in the output image.288 *289 * @since 0.33.0290 *291 * @example292 * const dataWithMergedExif = await sharp(inputWithExif)293 * .withExifMerge({294 * IFD0: {295 * Copyright: 'The National Gallery'296 * }297 * })298 * .toBuffer();299 *300 * @param {Object<string, Object<string, string>>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data.301 * @returns {Sharp}302 * @throws {Error} Invalid parameters303 */304function withExifMerge (exif) {305 this.withExif(exif);306 this.options.withExifMerge = true;307 return this;308}309 310/**311 * Keep ICC profile from the input image in the output image.312 *313 * When input and output colour spaces differ, use with {@link /api-colour/#tocolourspace toColourspace} and optionally {@link /api-colour/#pipelinecolourspace pipelineColourspace}.314 *315 * @since 0.33.0316 *317 * @example318 * const outputWithIccProfile = await sharp(inputWithIccProfile)319 * .keepIccProfile()320 * .toBuffer();321 *322 * @example323 * const cmykOutputWithIccProfile = await sharp(cmykInputWithIccProfile)324 * .pipelineColourspace('cmyk')325 * .toColourspace('cmyk')326 * .keepIccProfile()327 * .toBuffer();328 *329 * @returns {Sharp}330 */331function keepIccProfile () {332 this.options.keepMetadata |= 0b01000;333 return this;334}335 336/**337 * Transform using an ICC profile and attach to the output image.338 *339 * This can either be an absolute filesystem path or340 * built-in profile name (`srgb`, `p3`, `cmyk`).341 *342 * @since 0.33.0343 *344 * @example345 * const outputWithP3 = await sharp(input)346 * .withIccProfile('p3')347 * .toBuffer();348 *349 * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk).350 * @param {Object} [options]351 * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata?352 * @returns {Sharp}353 * @throws {Error} Invalid parameters354 */355function withIccProfile (icc, options) {356 if (is.string(icc)) {357 this.options.withIccProfile = icc;358 } else {359 throw is.invalidParameterError('icc', 'string', icc);360 }361 this.keepIccProfile();362 if (is.object(options)) {363 if (is.defined(options.attach)) {364 if (is.bool(options.attach)) {365 if (!options.attach) {366 this.options.keepMetadata &= ~0b01000;367 }368 } else {369 throw is.invalidParameterError('attach', 'boolean', options.attach);370 }371 }372 }373 return this;374}375 376/**377 * If the input contains gain map metadata, attempt to process the image and gain map separately,378 * recombining them into a single output image.379 *380 * This approach is faster and should produce better results than {@link #withgainmap withGainMap},381 * however not all operations are supported.382 *383 * Only JPEG input and output are supported.384 * JPEG output options other than `quality` are ignored.385 *386 * This feature is experimental and the API may change.387 *388 * @since 0.35.0389 *390 * @example391 * const outputWithResizedGainMap = await sharp(inputWithGainMap)392 * .keepGainMap()393 * .resize({ width: 64 })394 * .toBuffer();395 *396 * @returns {Sharp}397 */398function keepGainMap() {399 this.options.keepGainMap = true;400 this.options.withGainMap = false;401 this.options.keepMetadata |= 0b100000;402 return this;403}404 405/**406 * If the input contains gain map metadata, use it to convert the main image to HDR (High Dynamic Range) before further processing.407 * The input gain map is discarded.408 *409 * If the output is JPEG, generate and attach a new ISO 21496-1 gain map.410 * JPEG output options other than `quality` are ignored.411 *412 * This feature is experimental and the API may change.413 *414 * @since 0.35.0415 *416 * @example417 * const outputWithRegeneratedGainMap = await sharp(inputWithGainMap)418 * .withGainMap()419 * .toBuffer();420 *421 * @returns {Sharp}422 */423function withGainMap() {424 this.options.withGainMap = true;425 this.options.keepGainMap = false;426 this.options.colourspace = 'scrgb';427 return this;428}429 430/**431 * Keep XMP metadata from the input image in the output image.432 *433 * @since 0.34.3434 *435 * @example436 * const outputWithXmp = await sharp(inputWithXmp)437 * .keepXmp()438 * .toBuffer();439 *440 * @returns {Sharp}441 */442function keepXmp () {443 this.options.keepMetadata |= 0b00010;444 return this;445}446 447/**448 * Set XMP metadata in the output image.449 *450 * Supported by PNG, JPEG, WebP, and TIFF output.451 *452 * @since 0.34.3453 *454 * @example455 * const xmpString = `456 * <?xml version="1.0"?>457 * <x:xmpmeta xmlns:x="adobe:ns:meta/">458 * <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">459 * <rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">460 * <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator>461 * </rdf:Description>462 * </rdf:RDF>463 * </x:xmpmeta>`;464 *465 * const data = await sharp(input)466 * .withXmp(xmpString)467 * .toBuffer();468 *469 * @param {string} xmp String containing XMP metadata to be embedded in the output image.470 * @returns {Sharp}471 * @throws {Error} Invalid parameters472 */473function withXmp (xmp) {474 if (is.string(xmp) && xmp.length > 0) {475 this.options.withXmp = xmp;476 this.options.keepMetadata |= 0b00010;477 } else {478 throw is.invalidParameterError('xmp', 'non-empty string', xmp);479 }480 return this;481}482 483/**484 * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image.485 *486 * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent487 * sRGB colour space and strip all metadata, including the removal of any ICC profile.488 *489 * @since 0.33.0490 *491 * @example492 * const outputWithMetadata = await sharp(inputWithMetadata)493 * .keepMetadata()494 * .toBuffer();495 *496 * @returns {Sharp}497 */498function keepMetadata () {499 this.options.keepMetadata |= 0b11111;500 return this;501}502 503/**504 * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image.505 *506 * This will also convert to and add a web-friendly sRGB ICC profile if appropriate.507 *508 * Allows orientation and density to be set or updated.509 *510 * @example511 * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata)512 * .withMetadata()513 * .toBuffer();514 *515 * @example516 * // Set output metadata to 96 DPI517 * const data = await sharp(input)518 * .withMetadata({ density: 96 })519 * .toBuffer();520 *521 * @param {Object} [options]522 * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8.523 * @param {number} [options.density] Number of pixels per inch (DPI).524 * @returns {Sharp}525 * @throws {Error} Invalid parameters526 */527function withMetadata (options) {528 this.keepMetadata();529 this.withIccProfile('srgb');530 if (is.object(options)) {531 if (is.defined(options.orientation)) {532 if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) {533 this.options.withMetadataOrientation = options.orientation;534 } else {535 throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation);536 }537 }538 if (is.defined(options.density)) {539 if (is.number(options.density) && options.density > 0) {540 this.options.withMetadataDensity = options.density;541 } else {542 throw is.invalidParameterError('density', 'positive number', options.density);543 }544 }545 if (is.defined(options.icc)) {546 this.withIccProfile(options.icc);547 }548 if (is.defined(options.exif)) {549 this.withExifMerge(options.exif);550 }551 }552 return this;553}554 555/**556 * Force output to a given format.557 *558 * @example559 * // Convert any input to PNG output560 * const data = await sharp(input)561 * .toFormat('png')562 * .toBuffer();563 *564 * @param {(string|Object)} format - as a string or an Object with an 'id' attribute565 * @param {Object} options - output options566 * @returns {Sharp}567 * @throws {Error} unsupported format or options568 */569function toFormat (format, options) {570 const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase());571 if (!actualFormat) {572 throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format);573 }574 return this[actualFormat](options);575}576 577/**578 * Use these JPEG options for output image.579 *580 * @example581 * // Convert any input to very high quality JPEG output582 * const data = await sharp(input)583 * .jpeg({584 * quality: 100,585 * chromaSubsampling: '4:4:4'586 * })587 * .toBuffer();588 *589 * @example590 * // Use mozjpeg to reduce output JPEG file size (slower)591 * const data = await sharp(input)592 * .jpeg({ mozjpeg: true })593 * .toBuffer();594 *595 * @param {Object} [options] - output options596 * @param {number} [options.quality=80] - quality, integer 1-100597 * @param {boolean} [options.progressive=false] - use progressive (interlace) scan598 * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling599 * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables600 * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding601 * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }`602 * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation603 * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing604 * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive605 * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans606 * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8607 * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable608 * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format609 * @returns {Sharp}610 * @throws {Error} Invalid options611 */612function jpeg (options) {613 if (is.object(options)) {614 if (is.defined(options.quality)) {615 if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {616 this.options.jpegQuality = options.quality;617 } else {618 throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);619 }620 }621 if (is.defined(options.progressive)) {622 this._setBooleanOption('jpegProgressive', options.progressive);623 }624 if (is.defined(options.chromaSubsampling)) {625 if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {626 this.options.jpegChromaSubsampling = options.chromaSubsampling;627 } else {628 throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);629 }630 }631 const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding;632 if (is.defined(optimiseCoding)) {633 this._setBooleanOption('jpegOptimiseCoding', optimiseCoding);634 }635 if (is.defined(options.mozjpeg)) {636 if (is.bool(options.mozjpeg)) {637 if (options.mozjpeg) {638 this.options.jpegTrellisQuantisation = true;639 this.options.jpegOvershootDeringing = true;640 this.options.jpegOptimiseScans = true;641 this.options.jpegProgressive = true;642 this.options.jpegQuantisationTable = 3;643 }644 } else {645 throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg);646 }647 }648 const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation;649 if (is.defined(trellisQuantisation)) {650 this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation);651 }652 if (is.defined(options.overshootDeringing)) {653 this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing);654 }655 const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans;656 if (is.defined(optimiseScans)) {657 this._setBooleanOption('jpegOptimiseScans', optimiseScans);658 if (optimiseScans) {659 this.options.jpegProgressive = true;660 }661 }662 const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable;663 if (is.defined(quantisationTable)) {664 if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) {665 this.options.jpegQuantisationTable = quantisationTable;666 } else {667 throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable);668 }669 }670 }671 return this._updateFormatOut('jpeg', options);672}673 674/**675 * Use these PNG options for output image.676 *677 * By default, PNG output is full colour at 8 bits per pixel.678 *679 * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel.680 * Set `palette` to `true` for slower, indexed PNG output.681 *682 * For 16 bits per pixel output, convert to `rgb16` via683 * {@link /api-colour/#tocolourspace toColourspace}.684 *685 * @example686 * // Convert any input to full colour PNG output687 * const data = await sharp(input)688 * .png()689 * .toBuffer();690 *691 * @example692 * // Convert any input to indexed PNG output (slower)693 * const data = await sharp(input)694 * .png({ palette: true })695 * .toBuffer();696 *697 * @example698 * // Output 16 bits per pixel RGB(A)699 * const data = await sharp(input)700 * .toColourspace('rgb16')701 * .png()702 * .toBuffer();703 *704 * @param {Object} [options]705 * @param {boolean} [options.progressive=false] - use progressive (interlace) scan706 * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest)707 * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering708 * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support709 * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true`710 * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true`711 * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true`712 * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true`713 * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true`714 * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format715 * @returns {Sharp}716 * @throws {Error} Invalid options717 */718function png (options) {719 if (is.object(options)) {720 if (is.defined(options.progressive)) {721 this._setBooleanOption('pngProgressive', options.progressive);722 }723 if (is.defined(options.compressionLevel)) {724 if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) {725 this.options.pngCompressionLevel = options.compressionLevel;726 } else {727 throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel);728 }729 }730 if (is.defined(options.adaptiveFiltering)) {731 this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering);732 }733 const colours = options.colours || options.colors;734 if (is.defined(colours)) {735 if (is.integer(colours) && is.inRange(colours, 2, 256)) {736 this.options.pngBitdepth = bitdepthFromColourCount(colours);737 } else {738 throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);739 }740 }741 if (is.defined(options.palette)) {742 this._setBooleanOption('pngPalette', options.palette);743 } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) {744 this._setBooleanOption('pngPalette', true);745 }746 if (this.options.pngPalette) {747 if (is.defined(options.quality)) {748 if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) {749 this.options.pngQuality = options.quality;750 } else {751 throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality);752 }753 }754 if (is.defined(options.effort)) {755 if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) {756 this.options.pngEffort = options.effort;757 } else {758 throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);759 }760 }761 if (is.defined(options.dither)) {762 if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {763 this.options.pngDither = options.dither;764 } else {765 throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);766 }767 }768 }769 }770 return this._updateFormatOut('png', options);771}772 773/**774 * Use these WebP options for output image.775 *776 * @example777 * // Convert any input to lossless WebP output778 * const data = await sharp(input)779 * .webp({ lossless: true })780 * .toBuffer();781 *782 * @example783 * // Optimise the file size of an animated WebP784 * const outputWebp = await sharp(inputWebp, { animated: true })785 * .webp({ effort: 6 })786 * .toBuffer();787 *788 * @param {Object} [options] - output options789 * @param {number} [options.quality=80] - quality, integer 1-100790 * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100791 * @param {boolean} [options.lossless=false] - use lossless compression mode792 * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode793 * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling794 * @param {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow)795 * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text796 * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest)797 * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation798 * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)799 * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow)800 * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow)801 * @param {boolean} [options.exact=false] - preserve the colour data in transparent pixels802 * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format803 * @returns {Sharp}804 * @throws {Error} Invalid options805 */806function webp (options) {807 if (is.object(options)) {808 if (is.defined(options.quality)) {809 if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {810 this.options.webpQuality = options.quality;811 } else {812 throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);813 }814 }815 if (is.defined(options.alphaQuality)) {816 if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) {817 this.options.webpAlphaQuality = options.alphaQuality;818 } else {819 throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality);820 }821 }822 if (is.defined(options.lossless)) {823 this._setBooleanOption('webpLossless', options.lossless);824 }825 if (is.defined(options.nearLossless)) {826 this._setBooleanOption('webpNearLossless', options.nearLossless);827 }828 if (is.defined(options.smartSubsample)) {829 this._setBooleanOption('webpSmartSubsample', options.smartSubsample);830 }831 if (is.defined(options.smartDeblock)) {832 this._setBooleanOption('webpSmartDeblock', options.smartDeblock);833 }834 if (is.defined(options.preset)) {835 if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) {836 this.options.webpPreset = options.preset;837 } else {838 throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset);839 }840 }841 if (is.defined(options.effort)) {842 if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) {843 this.options.webpEffort = options.effort;844 } else {845 throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort);846 }847 }848 if (is.defined(options.minSize)) {849 this._setBooleanOption('webpMinSize', options.minSize);850 }851 if (is.defined(options.mixed)) {852 this._setBooleanOption('webpMixed', options.mixed);853 }854 if (is.defined(options.exact)) {855 this._setBooleanOption('webpExact', options.exact);856 }857 }858 trySetAnimationOptions(options, this.options);859 return this._updateFormatOut('webp', options);860}861 862/**863 * Use these GIF options for the output image.864 *865 * The first entry in the palette is reserved for transparency.866 *867 * The palette of the input image will be re-used if possible.868 *869 * @since 0.30.0870 *871 * @example872 * // Convert PNG to GIF873 * await sharp(pngBuffer)874 * .gif()875 * .toBuffer();876 *877 * @example878 * // Convert animated WebP to animated GIF879 * await sharp('animated.webp', { animated: true })880 * .toFile('animated.gif');881 *882 * @example883 * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF884 * const out = await sharp('in.gif', { animated: true })885 * .resize({ width: 128, height: 128 })886 * .gif({ dither: 0 })887 * .toBuffer();888 *889 * @example890 * // Lossy file size reduction of animated GIF891 * await sharp('in.gif', { animated: true })892 * .gif({ interFrameMaxError: 8 })893 * .toFile('optim.gif');894 *895 * @param {Object} [options] - output options896 * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow)897 * @param {boolean} [options.progressive=false] - use progressive (interlace) scan898 * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256899 * @param {number} [options.colors=256] - alternative spelling of `options.colours`900 * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest)901 * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most)902 * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32903 * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256904 * @param {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them905 * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation906 * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds)907 * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format908 * @returns {Sharp}909 * @throws {Error} Invalid options910 */911function gif (options) {912 if (is.object(options)) {913 if (is.defined(options.reuse)) {914 this._setBooleanOption('gifReuse', options.reuse);915 }916 if (is.defined(options.progressive)) {917 this._setBooleanOption('gifProgressive', options.progressive);918 }919 const colours = options.colours || options.colors;920 if (is.defined(colours)) {921 if (is.integer(colours) && is.inRange(colours, 2, 256)) {922 this.options.gifBitdepth = bitdepthFromColourCount(colours);923 } else {924 throw is.invalidParameterError('colours', 'integer between 2 and 256', colours);925 }926 }927 if (is.defined(options.effort)) {928 if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) {929 this.options.gifEffort = options.effort;930 } else {931 throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort);932 }933 }934 if (is.defined(options.dither)) {935 if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) {936 this.options.gifDither = options.dither;937 } else {938 throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither);939 }940 }941 if (is.defined(options.interFrameMaxError)) {942 if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) {943 this.options.gifInterFrameMaxError = options.interFrameMaxError;944 } else {945 throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError);946 }947 }948 if (is.defined(options.interPaletteMaxError)) {949 if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) {950 this.options.gifInterPaletteMaxError = options.interPaletteMaxError;951 } else {952 throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError);953 }954 }955 if (is.defined(options.keepDuplicateFrames)) {956 if (is.bool(options.keepDuplicateFrames)) {957 this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames);958 } else {959 throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames);960 }961 }962 }963 trySetAnimationOptions(options, this.options);964 return this._updateFormatOut('gif', options);965}966 967/**968 * Use these JP2 options for output image.969 *970 * Requires libvips compiled with support for OpenJPEG.971 * The prebuilt binaries do not include this - see972 * {@link /install#custom-libvips installing a custom libvips}.973 *974 * @example975 * // Convert any input to lossless JP2 output976 * const data = await sharp(input)977 * .jp2({ lossless: true })978 * .toBuffer();979 *980 * @example981 * // Convert any input to very high quality JP2 output982 * const data = await sharp(input)983 * .jp2({984 * quality: 100,985 * chromaSubsampling: '4:4:4'986 * })987 * .toBuffer();988 *989 * @since 0.29.1990 *991 * @param {Object} [options] - output options992 * @param {number} [options.quality=80] - quality, integer 1-100993 * @param {boolean} [options.lossless=false] - use lossless compression mode994 * @param {number} [options.tileWidth=512] - horizontal tile size995 * @param {number} [options.tileHeight=512] - vertical tile size996 * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling997 * @returns {Sharp}998 * @throws {Error} Invalid options999 */1000function jp2 (options) {1001 /* node:coverage ignore next 41 */1002 if (!this.constructor.format.jp2.output.buffer) {1003 throw errJp2Save();1004 }1005 if (is.object(options)) {1006 if (is.defined(options.quality)) {1007 if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {1008 this.options.jp2Quality = options.quality;1009 } else {1010 throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);1011 }1012 }1013 if (is.defined(options.lossless)) {1014 if (is.bool(options.lossless)) {1015 this.options.jp2Lossless = options.lossless;1016 } else {1017 throw is.invalidParameterError('lossless', 'boolean', options.lossless);1018 }1019 }1020 if (is.defined(options.tileWidth)) {1021 if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) {1022 this.options.jp2TileWidth = options.tileWidth;1023 } else {1024 throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth);1025 }1026 }1027 if (is.defined(options.tileHeight)) {1028 if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) {1029 this.options.jp2TileHeight = options.tileHeight;1030 } else {1031 throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight);1032 }1033 }1034 if (is.defined(options.chromaSubsampling)) {1035 if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) {1036 this.options.jp2ChromaSubsampling = options.chromaSubsampling;1037 } else {1038 throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling);1039 }1040 }1041 }1042 return this._updateFormatOut('jp2', options);1043}1044 1045/**1046 * Set animation options if available.1047 * @private1048 *1049 * @param {Object} [source] - output options1050 * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation1051 * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds)1052 * @param {Object} [target] - target object for valid options1053 * @throws {Error} Invalid options1054 */1055function trySetAnimationOptions (source, target) {1056 if (is.object(source) && is.defined(source.loop)) {1057 if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) {1058 target.loop = source.loop;1059 } else {1060 throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop);1061 }1062 }1063 if (is.object(source) && is.defined(source.delay)) {1064 // We allow singular values as well1065 if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) {1066 target.delay = [source.delay];1067 } else if (1068 Array.isArray(source.delay) &&1069 source.delay.every(is.integer) &&1070 source.delay.every(v => is.inRange(v, 0, 65535))) {1071 target.delay = source.delay;1072 } else {1073 throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay);1074 }1075 }1076}1077 1078/**1079 * Use these TIFF options for output image.1080 *1081 * The `density` can be set in pixels/inch via {@link #withmetadata withMetadata}1082 * instead of providing `xres` and `yres` in pixels/mm.1083 *1084 * @example1085 * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output1086 * sharp('input.svg')1087 * .tiff({1088 * compression: 'lzw',1089 * bitdepth: 11090 * })1091 * .toFile('1-bpp-output.tiff')1092 * .then(info => { ... });1093 *1094 * @param {Object} [options] - output options1095 * @param {number} [options.quality=80] - quality, integer 1-1001096 * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format1097 * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k1098 * @param {boolean} [options.bigtiff=false] - use BigTIFF variant (has no effect when compression is none)1099 * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float1100 * @param {boolean} [options.pyramid=false] - write an image pyramid1101 * @param {boolean} [options.tile=false] - write a tiled tiff1102 * @param {number} [options.tileWidth=256] - horizontal tile size, valid values are integers in the range 1-327681103 * @param {number} [options.tileHeight=256] - vertical tile size, valid values are integers in the range 1-327681104 * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm, valid values are numbers in the range 0.001-10000001105 * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm, valid values are numbers in the range 0.001-10000001106 * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm1107 * @param {number} [options.bitdepth=0] - reduce bitdepth to 1, 2 or 4 bit1108 * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite1109 * @returns {Sharp}1110 * @throws {Error} Invalid options1111 */1112function tiff (options) {1113 if (is.object(options)) {1114 if (is.defined(options.quality)) {1115 if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) {1116 this.options.tiffQuality = options.quality;1117 } else {1118 throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality);1119 }1120 }1121 if (is.defined(options.bitdepth)) {1122 if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4])) {1123 this.options.tiffBitdepth = options.bitdepth;1124 } else {1125 throw is.invalidParameterError('bitdepth', '1, 2 or 4', options.bitdepth);1126 }1127 }1128 // tiling1129 if (is.defined(options.tile)) {1130 this._setBooleanOption('tiffTile', options.tile);1131 }1132 if (is.defined(options.tileWidth)) {1133 if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) {1134 this.options.tiffTileWidth = options.tileWidth;1135 } else {1136 throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth);1137 }1138 }1139 if (is.defined(options.tileHeight)) {1140 if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) {1141 this.options.tiffTileHeight = options.tileHeight;1142 } else {1143 throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight);1144 }1145 }1146 // miniswhite1147 if (is.defined(options.miniswhite)) {1148 this._setBooleanOption('tiffMiniswhite', options.miniswhite);1149 }1150 // pyramid1151 if (is.defined(options.pyramid)) {1152 this._setBooleanOption('tiffPyramid', options.pyramid);1153 }1154 // resolution1155 if (is.defined(options.xres)) {1156 if (is.number(options.xres) && is.inRange(options.xres, 0.001, 1000000)) {1157 this.options.tiffXres = options.xres;1158 } else {1159 throw is.invalidParameterError('xres', 'number between 0.001 and 1000000', options.xres);1160 }1161 }1162 if (is.defined(options.yres)) {1163 if (is.number(options.yres) && is.inRange(options.yres, 0.001, 1000000)) {1164 this.options.tiffYres = options.yres;1165 } else {1166 throw is.invalidParameterError('yres', 'number between 0.001 and 1000000', options.yres);1167 }1168 }1169 // compression1170 if (is.defined(options.compression)) {1171 if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) {1172 this.options.tiffCompression = options.compression;1173 } else {1174 throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression);1175 }1176 }1177 // bigtiff1178 if (is.defined(options.bigtiff)) {1179 this._setBooleanOption('tiffBigtiff', options.bigtiff);1180 }1181 // predictor1182 if (is.defined(options.predictor)) {1183 if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) {1184 this.options.tiffPredictor = options.predictor;1185 } else {1186 throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor);1187 }1188 }1189 // resolutionUnit1190 if (is.defined(options.resolutionUnit)) {1191 if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) {1192 this.options.tiffResolutionUnit = options.resolutionUnit;1193 } else {1194 throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit);1195 }1196 }1197 }1198 return this._updateFormatOut('tiff', options);1199}1200 