import java.awt.image.Raster; //导入方法依赖的package包/类
/** Encode an image to JPEG **/
public ByteBuffer encode(Raster img, int quality) throws TurboJpegException {
Pointer codec = null;
Pointer bufPtr = null;
try {
TJPF pixelFmt;
switch (img.getNumBands()) {
case 4:
pixelFmt = TJPF.TJPF_BGRX; // 4BYTE_BGRA
break;
case 3:
pixelFmt = TJPF.TJPF_BGR; // 3BYTE_BGR
break;
case 1:
pixelFmt = TJPF.TJPF_GRAY; // 1BYTE_GRAY
break;
default:
throw new IllegalArgumentException("Illegal sample format");
}
TJSAMP sampling = pixelFmt == TJPF.TJPF_GRAY ? TJSAMP.TJSAMP_GRAY : TJSAMP.TJSAMP_444;
codec = lib.tjInitCompress();
// Allocate JPEG target buffer
int bufSize = (int) lib.tjBufSize(img.getWidth(), img.getHeight(), sampling);
bufPtr = lib.tjAlloc(bufSize);
NativeLongByReference lenPtr = new NativeLongByReference(bufSize);
// Wrap source image data buffer with ByteBuffer to pass it over the ABI
ByteBuffer inBuf = ByteBuffer.wrap(((DataBufferByte) img.getDataBuffer()).getData())
.order(runtime.byteOrder());
int rv = lib.tjCompress2(
codec, inBuf, img.getWidth(), 0, img.getHeight(), pixelFmt,
new PointerByReference(bufPtr), lenPtr, sampling, quality, 0);
if (rv != 0) {
LOG.error("Could not compress image (dimensions: {}x{}, format: {}, sampling: {}, quality: {}",
img.getWidth(), img.getHeight(), pixelFmt, sampling, quality);
throw new TurboJpegException(lib.tjGetErrorStr());
}
ByteBuffer outBuf = ByteBuffer.allocate(lenPtr.getValue().intValue()).order(runtime.byteOrder());
bufPtr.get(0, outBuf.array(), 0, lenPtr.getValue().intValue());
outBuf.rewind();
return outBuf;
} finally {
if (codec != null && codec.address() != 0) lib.tjDestroy(codec);
if (bufPtr != null && bufPtr.address() != 0) lib.tjFree(bufPtr);
}
}