#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = 'helljump'

import logging
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui


log = logging.getLogger(__name__)


def border(pm, w, c):
    assert isinstance(pm, QtGui.QPixmap)
    if pm.width() < w or pm.height() < w:
        return pm
    canvas = QtGui.QPixmap(pm.width(), pm.height())
    canvas.fill(QtGui.QColor(c))
    painter = QtGui.QPainter()
    painter.begin(canvas)
    painter.drawPixmap(w, w, pm, w, w, pm.width()-w*2, pm.height()-w*2)
    painter.end()
    return canvas


def resize(pm, w, h):
    assert isinstance(pm, QtGui.QPixmap)
    if pm.width() > w or pm.height() > h:
        pm = pm.scaled(w, h, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
    return pm


def rotate(pm, a):
    assert isinstance(pm, QtGui.QPixmap)
    t = QtGui.QTransform()
    t.rotate(a)
    return pm.transformed(t, QtCore.Qt.SmoothTransformation)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    img = QtGui.QPixmap(r'd:\work2014\cm3\_test\img.jpg')
    img = rotate(img, 31)
    img = resize(img, 320, 240)
    img = border(img, 15, '#fff')
    img.save(r'd:\work2014\cm3\_test\img_b.jpg', quality=95)
