DLLEXPORT int tj3SetCroppingRegion()

in turbojpeg.c [1916:1963]


DLLEXPORT int tj3SetCroppingRegion(tjhandle handle, tjregion croppingRegion)
{
  static const char FUNCTION_NAME[] = "tj3SetCroppingRegion";
  int retval = 0, scaledWidth, scaledHeight;

  GET_TJINSTANCE(handle, -1);
  if ((this->init & DECOMPRESS) == 0)
    THROW("Instance has not been initialized for decompression");

  if (croppingRegion.x == 0 && croppingRegion.y == 0 &&
      croppingRegion.w == 0 && croppingRegion.h == 0) {
    this->croppingRegion = croppingRegion;
    return 0;
  }

  if (croppingRegion.x < 0 || croppingRegion.y < 0 || croppingRegion.w < 0 ||
      croppingRegion.h < 0)
    THROW("Invalid cropping region");
  if (this->jpegWidth < 0 || this->jpegHeight < 0)
    THROW("JPEG header has not yet been read");
  if (this->precision == 16 || this->lossless)
    THROW("Cannot partially decompress lossless JPEG images");
  if (this->subsamp == TJSAMP_UNKNOWN)
    THROW("Could not determine subsampling level of JPEG image");

  scaledWidth = TJSCALED(this->jpegWidth, this->scalingFactor);
  scaledHeight = TJSCALED(this->jpegHeight, this->scalingFactor);

  if (croppingRegion.x %
      TJSCALED(tjMCUWidth[this->subsamp], this->scalingFactor) != 0)
    THROWI("The left boundary of the cropping region (%d) is not\n"
           "divisible by the scaled iMCU width (%d)",
           croppingRegion.x,
           TJSCALED(tjMCUWidth[this->subsamp], this->scalingFactor));
  if (croppingRegion.w == 0)
    croppingRegion.w = scaledWidth - croppingRegion.x;
  if (croppingRegion.h == 0)
    croppingRegion.h = scaledHeight - croppingRegion.y;
  if (croppingRegion.w <= 0 || croppingRegion.h <= 0 ||
      croppingRegion.x + croppingRegion.w > scaledWidth ||
      croppingRegion.y + croppingRegion.h > scaledHeight)
    THROW("The cropping region exceeds the scaled image dimensions");

  this->croppingRegion = croppingRegion;

bailout:
  return retval;
}