Backend API. Server-side code: this runs in a Codename One backend, not in the app on the device.

public final class JpegCodec

  1. Object
  2. JpegCodec

Reads and writes JPEG files in pure Java.

[#decode(byte[])] reads baseline and progressive Huffman-coded JPEG (JFIF, Exif and Adobe files) with any chroma subsampling, restart intervals, 8- and 16-bit quantization tables, gray, YCbCr and Adobe CMYK/YCCK color. Arithmetic coding and 12-bit lossless JPEG are not supported. Chroma is upsampled by replication, so a decode may differ from libjpeg’s by a few levels near sharp color edges.

encode(RasterImage, float, boolean) writes baseline JPEG with the standard tables of the JPEG specification, 4:4:4 (no chroma subsampling), scaled to a quality the way libjpeg scales them, so quality 0.75 here gives the same tables as libjpeg’s (and Pillow’s) quality 75. Alpha is dropped.

Methods

public static boolean isJpeg(byte[] data)Returns true when data starts with a JPEG start-of-image marker.
public static int componentCount(byte[] data)Returns the number of color components of a JPEG file: 1 for gray, 3 for color, 4 for CMYK, or 0 when no frame header is found.
public static RasterImage decode(byte[] data) throws IOExceptionDecodes a JPEG file to an opaque ARGB image.
public static byte[] encode(RasterImage img, float quality)Encodes an image as baseline color JPEG.
public static byte[] encode(RasterImage img, float quality, boolean grayscale)Encodes an image as baseline JPEG.

Inherited methods

Method details

isJpeg

public static boolean isJpeg(byte[] data)
Returns true when data starts with a JPEG start-of-image marker.

Parameters

data byte[]
file bytes

Returns

whether the data looks like a JPEG file

componentCount

public static int componentCount(byte[] data)
Returns the number of color components of a JPEG file: 1 for gray, 3 for color, 4 for CMYK, or 0 when no frame header is found.

Parameters

data byte[]
the file

Returns

the component count

decode

public static RasterImage decode(byte[] data) throws IOException
Decodes a JPEG file to an opaque ARGB image.

Parameters

data byte[]
the file

Returns

the image

Throws

IOException
when the data is not a JPEG file this codec can read

encode

public static byte[] encode(RasterImage img, float quality)
Encodes an image as baseline color JPEG.

Parameters

img RasterImage
the image; alpha is ignored
quality float
0 to 1, as libjpeg’s 0 to 100 divided by 100

Returns

the JPEG file

encode

public static byte[] encode(RasterImage img, float quality, boolean grayscale)
Encodes an image as baseline JPEG.

Parameters

img RasterImage
the image; alpha is ignored
quality float
0 to 1, as libjpeg’s 0 to 100 divided by 100
grayscale boolean
true to write one gray component (the luma of each pixel) instead of three

Returns

the JPEG file