#include "imagebuffer.h"
#include "imageutils.h"

void adjustAlpha(QImage &img)
{
    if(img.isNull())
        return;

    unsigned int *data = (unsigned int *)img.bits();
    unsigned char alpha, r, g, b;
    int i;
    int len = img.width()*img.height();
    for(i=0; i < len; ++i){
        alpha = qAlpha(data[i]);
        if(alpha != 255 && alpha != 0){
            float srcPercent = ((float)alpha)/255.0;
            int destVal = (int)((1.0-srcPercent)*255);
            r = (int)((srcPercent*qRed(data[i])) + destVal);
            g = (int)((srcPercent*qGreen(data[i])) + destVal);
            b = (int)((srcPercent*qBlue(data[i])) + destVal);
            data[i] = qRgba(r, g, b, 255);
        }
    }
}


KIFImage::KIFImage(QObject *parent, const char *name)
    : QObject(parent, name)
{
    ;
}

KIFImage::~KIFImage()
{

}

void KIFImage::slotSetFile(const QString &fileName)
{
    if(!loadImage(mainImg, fileName)){
        emit invalidFile();
        return;
    }
    else if(mainImg.depth() < 32)
        mainImg = mainImg.convertDepth(32);

    adjustAlpha(mainImg);
    emit updated();
}

void KIFImage::setImage(QImage *img)
{
    mainImg = *img;
    if(mainImg.depth() < 32)
        mainImg = mainImg.convertDepth(32);
    emit updated();
}

void KIFImage::slotUpdateFromImage()
{
    emit updated();
}


