<?php

class JpgImage extends CComponent
{
  private $handle;

  public function __construct()
  {
    $this->handle = NULL;
  }

  public function load($path)
  {
//    if(!file_exists($path))
//      throw new CHttpException(404, 'Invalid request. File not found.');

    if($this->handle)
    {
      imagedestroy($this->handle);
      $this->handle = NULL;
    }
    $this->handle = imagecreatefromjpeg($path);
  }

  public function create($w, $h)
  {
    if($this->handle)
    {
      imagedestroy($this->handle);
      $this->handle = NULL;
    }
    $this->handle = imagecreatetruecolor($w, $h);
  }

  public function getHandle()
  {
    return $this->handle;
  }

  public function setHandle($handle)
  {
    $this->handle = $handle;
  }
  
  public function width()
  {
    if($this->handle)
      return imagesx($this->handle);
    else
      return -1;
  }

  public function height()
  {
    if($this->handle)
      return imagesy($this->handle);
    else
      return -1;
  }

  public function legalizeX($x)
  {
    return $this->stayInRange($x, 0, $this->width());
  }

  public function legalizeY($y)
  {
    return $this->stayInRange($y, 0, $this->height());
  }

  public function legalizeWidth($x, $w)
  {
    $x = $this->legalizeX($x);
    $w = $this->legalizeX($w);
    return $this->stayInRange($w, 0, $this->width() - $x);
  }

  public function legalizeHeight($y, $h)
  {
    $y = $this->legalizeY($y);
    $h = $this->legalizeY($h);
    return $this->stayInRange($h, 0, $this->height() - $y);
  }

  public function stayInRange($value, $min, $max)
  {
    if($value < $min)
      $value = $min;
    else
    if($value > $max)
      $value = $max;
    return $value;
  }

  public function output($quality = 80)
  {
    return $this->save(NULL, $quality);
  }

  public function crop($x, $y, $w, $h)
  {
    $crop = new JpgImage();
    $crop->create($w, $h);
     
    if(imagecopyresampled(
         
        $crop->handle,
        $this->handle,
         
        0, 0,
         
        $x, $y,
         
        $w, $h,
         
        $w, $h
    ))
    {
      return $crop;
    }
     
    return null;
  }

  public function save($filename, $quality = 80)
  {
    return imagejpeg($this->handle, $filename, $quality);
  }

  function __destruct()
  {
    if($this->handle)
      imagedestroy($this->handle);
  }
}
