/*
  Image.cpp
  
  Author: Sergi Diaz Planas (2017)
*/
#include "Image.h"

// Constructor.
Image::Image() {}

// Decodes a given base64 string into a cv matrix. Stores
// the decoded matrix in a Image instance.
bool Image::load(std::string b64)
{
    // Try to decode input string. Return true if successful
    try
    {
        this->image = base_64_to_mat(b64);
        return true;
    }
    catch (int e)
    {
        return false;
    }
}

// Return the image as a base64 codifyed string.
std::string Image::base64()
{
    // Return an empty string if image is empty
    if(this->image.empty())
        return "";

    std::string b64 = mat_to_base64(this->image);
    return b64;
}

// Return true if image is empty.
bool Image::isEmpty()
{
    return this->image.empty();
}

// Return the image as a cv matrix.
cv::Mat Image::getImage()
{
    return this->image;
}

// Set given matrix.
void Image::setImage(cv::Mat image)
{
    this->image = image;
}

// Return an Image containing the original's fragment delimited
// by a rectangle at position (x,y) with width w and height h.
Image Image::crop(int x, int y, int w, int h)
{
    Image cropImage = Image();

    // Return an empty image if the original is also empty or
    // if given parameters don't match those of a valid rectangle.
    if (this->image.empty())
        return cropImage;
    if (x < 0 || y < 0)
        return cropImage;
    if (w > this->image.cols || h > this->image.rows)
        return cropImage;

    // Return the portion of the original image delimited by the
    // rectangle.
    cv::Rect rectangle = cv::Rect(x, y, w, h);
    cropImage.setImage(this->image(rectangle));
    return cropImage;
}

