Skip to content

k.utils.image ​

Image format, size and watermark

Execution ContextPrerequisitesTypical Use
KScript API, background jobsFileInfo overloads read/write site files via k.file; byte-array overloads work in memoryThumbnails, WebP conversion, watermarking, and print DPI adjustments

k.utils.image processes image byte arrays or site FileInfo objects in scripts (format conversion, resizing, DPI changes, watermarking, and animation frame tools).

Quick Start ​

js
k.api.post("convertThumb", () => {
  const source = k.file.readBinary("media/source.jpg")
  const resized = k.utils.image.resize(source, 240, 240)
  const webp = k.utils.image.changeFormat(resized, ".webp")
  k.file.writeBinary("media/source-thumb.webp", webp)
  return k.utils.image.getSize(webp)
})

Quick Reference ​

Method / PropertyDescriptionReturns
changeFormat(binary, newExtension)Convert image bytes to another format extensionnumber[]
resize(file, height, width[, saveAs])Resize a site image file and saveFileInfo
resize(image, height, width)Resize image bytes (0 keeps aspect ratio; never upscales)number[] | null
changeDpi(file, targetDpi[, saveAs])Update DPI (values below 72 clamp to 72) and saveFileInfo
addWatermark(binary, watermark, option)Apply a watermark image over base image bytesnumber[]
getSize(image)Read image width and heightImageSize
getFrameCount(image)Read GIF or WebP animation frame countnumber
convertToTwoFramesGif(image)Convert a static/single-frame image into a 2-frame looping GIF (>= 2 frames returned unchanged)number[] | null

changeFormat() ​

Convert image bytes to the format matching the target file extension.

ParameterTypeRequiredDescription
binarynumber[]YesSource image bytes, usually from k.file.readBinary() or an uploaded file
newExtensionstringYesTarget extension, such as .webp, .png, or .jpg

Returns: number[], the converted image bytes.

js
const jpg = k.file.readBinary("media/source.jpg")
const webp = k.utils.image.changeFormat(jpg, ".webp")

k.file.writeBinary("media/source.webp", webp)
return k.file.get("media/source.webp")

resize() ​

Resize a site FileInfo file or an image byte array.

OverloadDescription
resize(file, height, width, saveAs?)Resize a site file and return FileInfo
resize(image, height, width)Resize a byte array and return number[] | null
ParameterTypeRequiredDescription
fileFileInfoRequired for site file overloadSite file object, usually from k.file.get()
imagenumber[]Required for byte array overloadImage byte array
heightnumberYesTarget height. In the byte-array overload, pass 0 to calculate from width
widthnumberYesTarget width. In the byte-array overload, pass 0 to calculate from height
saveAsstringNoSite file path to save as; always pass a distinct path (omitting it attempts in-place overwrite while the source stream is still open)

Returns: resize(file, ...) returns FileInfo; resize(image, ...) returns number[] | null.

Runtime Edge Cases & Format Caveat

  • Byte-array overload never upscales: resize(image, height, width) returns an empty byte array (length === 0) when both target width and height exceed the source dimensions, returns null for undecodable bytes, and defaults to 90×90 when both height <= 0 and width <= 0. Check result && result.length > 0 before saving.
  • Always specify a distinct saveAs path: resize(file, height, width, saveAs?) keeps the read handle open when opening the output stream, so omitting saveAs to overwrite in place fails with an IOException on Windows.
  • Current file-overload output format caveat: That overload passes the dotted extension (for example .jpg) to the internal encoder, which expects dotless names (jpg, png, gif), causing it to fall back to WebP encoding. To guarantee a specific format, resize k.file.readBinary() bytes via the byte-array overload (and convert with changeFormat() if needed).

For a site file, load FileInfo with k.file.get() first and pass a separate saveAs path:

js
const original = k.file.get("media/product.jpg")
const resized = k.utils.image.resize(original, 600, 800, "media/product-800.webp")

return {
  url: resized.url,
  size: resized.size
}

For uploads or bytes returned by another API, use the byte-array overload and check that the result is non-empty:

js
const file = k.request.files[0]
const thumbnail = k.utils.image.resize(file.bytes, 240, 240)
if (thumbnail && thumbnail.length > 0) {
  k.file.writeBinary("media/thumbs/" + file.fileName, thumbnail)
}

changeDpi() ​

Modify the image DPI and save as a site file.

ParameterTypeRequiredDescription
fileUploadFile | FileInfoYesUploaded file or site file object
targetDpinumberYesTarget DPI; values below 72 are treated as 72
saveAsstringRequired for UploadFile, optional for FileInfoSave path. The FileInfo overload overwrites the source file when omitted

Returns: FileInfo, the saved site file.

js
const source = k.file.get("media/print-cover.jpg")
const output = k.utils.image.changeDpi(source, 300, "media/print-cover-300dpi.jpg")

return {
  path: output.fullName,
  size: output.size
}

addWatermark() ​

Add a watermark over image bytes; WatermarkOptions includes align, justify, opacity, offsetX, offsetY, and repeat.

ParameterTypeRequiredDescription
binarynumber[]YesBase image bytes
watermarknumber[]YesWatermark image bytes
optionWatermarkOptionsYesWatermark position, opacity, and repeat behavior

WatermarkOptions ​

PropertyTypeDescription
alignstringVertical position: top, center, bottom
justifystringHorizontal position: left, center, right
opacitynumberOpacity, usually from 0 to 1
offsetXnumberHorizontal offset ratio, for example 0.04 means 4%
offsetYnumberVertical offset ratio
repeatbooleanWhether to tile the watermark

Returns: number[], the watermarked image bytes.

js
const image = k.file.readBinary("media/product.jpg")
const watermark = k.file.readBinary("media/watermark.png")

const output = k.utils.image.addWatermark(image, watermark, {
  align: "bottom",
  justify: "right",
  offsetX: 0.04,
  offsetY: 0.04,
  opacity: 0.8,
  repeat: false
})

k.file.writeBinary("media/product-watermarked.jpg", output)

getSize() / getFrameCount() / convertToTwoFramesGif() ​

Read dimensions, frame count, or convert GIF animations.

MethodParameterReturnDescription
getSize(image)number[]ImageSize ({ width, height })Read image dimensions
getFrameCount(image)number[]numberRead GIF / WebP frame count
convertToTwoFramesGif(image)number[]number[] | nullConvert a single-frame/static image to a 2-frame looping GIF; returns input unchanged if frameCount >= 2, or null if invalid

Returns: getSize() returns { width, height }; getFrameCount() returns number; convertToTwoFramesGif() returns number[] | null.

js
const image = k.file.readBinary("media/banner.jpg")
const size = k.utils.image.getSize(image)

return {
  width: size.width,
  height: size.height
}

getFrameCount() reads GIF / WebP frame counts; convertToTwoFramesGif() duplicates the first frame of a single-frame or static image (frameCount < 2) into a 2-frame looping GIF, and returns the original bytes untouched when frameCount >= 2 (it does not transcode multi-frame WebP animations into GIF):

js
const source = k.file.readBinary("media/badge.png")
const frameCount = k.utils.image.getFrameCount(source)

if (frameCount < 2) {
  const gif = k.utils.image.convertToTwoFramesGif(source)
  if (gif) {
    k.file.writeBinary("media/badge-loop.gif", gif)
  }
}

TypeScript Definitions ​

ts
interface KImageUtility {
  changeFormat(Binary: number[], NewExtension: string): number[];
  changeDpi(file: UploadFile, targetDpi: number, saveAs: string): FileInfo;
  changeDpi(file: FileInfo, targetDpi: number, saveAs?: string): FileInfo;
  resize(file: FileInfo, height: number, width: number, saveAs?: string): FileInfo;
  resize(image: number[], height: number, width: number): number[] | null;
  addWatermark(binary: number[], watermark: number[], option: WatermarkOptions): number[];
  getSize(Image: number[]): ImageSize;
  getFrameCount(image: number[]): number;
  convertToTwoFramesGif(image: number[]): number[] | null;
}

interface WatermarkOptions {
  align: string;
  justify: string;
  opacity: number;
  offsetX: number;
  offsetY: number;
  repeat: boolean;
}

interface ImageSize {
  width: number;
  height: number;
}