浏览代码

Use Imagick if installed (closes #43)

Conflicts:
	SE/procesy5.php
Piotr Labudda 11 年之前
父节点
当前提交
435c8b85ba
共有 4 个文件被更改,包括 488 次插入459 次删除
  1. 9 20
      SE/procesy/ajax.php
  2. 35 62
      SE/procesy/index.php
  3. 44 98
      SE/procesy5.php
  4. 400 279
      SE/se-lib/DB_Image.php

+ 9 - 20
SE/procesy/ajax.php

@@ -1,5 +1,7 @@
 <?php
 
+Lib::loadClass('DB_Image');
+
 if (!class_exists('Lib')) die('404');
 
 function ajax_get_subtree() {
@@ -61,8 +63,6 @@ function ajax_add_image() {
 	$errors = array();
 	$msgs = array();
 
-	Lib::loadClass('DB_Image');
-
 	// check remote id
 	if ($remote_id <= 0) {
 		echo'<p>';
@@ -74,8 +74,7 @@ function ajax_add_image() {
 	}
 
 	// check remote table
-	$remote_tables = DB_Image::conf_get('remote_tables');
-	if (!in_array($remote_table, $remote_tables)) {
+	if (!DB_Image::tableIsAllowed($remote_table)) {
 		$errors[] = "Error table not allowed to add image";
 	}
 
@@ -100,7 +99,7 @@ function ajax_add_image() {
 		}
 
 		if (empty($errors)) {
-			$affected = DB_Image::delete_image($req['ID'], $req['REMOTE_TABLE'], $req['REMOTE_ID']);
+			$affected = DB_Image::deleteImage($req['ID'], $req['REMOTE_TABLE'], $req['REMOTE_ID']);
 			if ($affected == 1) {
 				$msgs[] = '<p>'."Usunieto zdjecie ID=".$req['ID'].'</p>';
 			} else {
@@ -114,7 +113,7 @@ function ajax_add_image() {
 		//echo '<p>Please select a file</p>';
 	}
 	else {
-		$errors = DB_Image::upload_image($remote_table, $remote_id, $_FILES['userfile']);
+		$errors = DB_Image::uploadImage($remote_table, $remote_id, $_FILES['userfile']);
 		// give praise and thanks to the php gods
 		if (empty($errors)) {
 			$msgs[] = '<p>Thank you for submitting</p>';
@@ -175,7 +174,7 @@ function ajax_add_image() {
 
 
 // TODO: show images, mv to function {
-	$images = DB_Image::get_images($thiss->DETECT_TABLE_NAME, $remote_id);
+	$images = DB_Image::getImages($thiss->DETECT_TABLE_NAME, $remote_id);
 
 	if (empty($images)) {
 		echo'<p class="err">'."Brak obrazkow".'</p>';
@@ -433,8 +432,6 @@ function ajax_show_images() {
 	$thiss = new stdClass();
 	$thiss->DETECT_TABLE_NAME = $remote_table;
 
-	Lib::loadClass('DB_Image');
-
 	// check remote id
 	if ($remote_id <= 0) {
 		header('HTTP/1.1 400: Bad Request');
@@ -450,16 +447,8 @@ function ajax_show_images() {
 		exit;
 	}
 
-	$db = DB::getDB();
-	$sql = "select `ID`, `TYPE`, `SIZE`, `DEST`
-		from `".DB_Image::conf_get_table_name()."`
-		where
-			`REMOTE_ID`='{$remote_id}'
-			and `REMOTE_TABLE`='{$remote_table}'
-	";
-
-	$res = $db->query($sql);
-	if (!$db->num_rows($res)) {
+	$images = DB_Image::getImages($remote_table, $remote_id);
+	if (!$images) {
 		header('HTTP/1.1 400: Bad Request');
 		header('Warning: images not found in db L.' . __LINE__);
 		exit;
@@ -467,7 +456,7 @@ function ajax_show_images() {
 
 	echo'<p>'."Zdjecia dla rekordu <b>{$remote_id}</b> z tabeli {$remote_table}".'</p>';
 
-	while ($r = $db->fetch($res)) {
+	foreach ($images as $r) {
 		$src = "?function_init=fun_SHOW_IMAGE&image_id={$r->ID}";
 		echo'<img src="'.$src.'" alt="'.$r->TYPE.'" />';
 	}

+ 35 - 62
SE/procesy/index.php

@@ -43,93 +43,66 @@ function fun_SHOW_EXTERNAL_IMAGE() {
 	$remote_table = V::get('tbl', '', $_REQUEST);
 	$remote_id = V::get('id', '', $_REQUEST, 'int');
 	$number = V::get('number', '', $_REQUEST, 'int');
-	$image_resize = V::get('resize', '', $_REQUEST);
+	$imageResize = V::get('resize', '', $_REQUEST);
+	$DBG = (V::get('DBG', 0, $_REQUEST, 'int') > 0);
 
 	Lib::loadClass('DB_Image');
 
-	// check remote id
 	if ($remote_id <= 0) {
 		header('HTTP/1.1 400: Bad Request');
 		header('Warning: wrong ID L.' . __LINE__);
 		exit;
 	}
 
-	// check remote table
-	$remote_tables = DB_Image::conf_get('remote_tables');
-	if (!in_array($remote_table, $remote_tables)) {
+	if (!DB_Image::tableIsAllowed($remote_table)) {
 		header('HTTP/1.1 400: Bad Request');
 		header('Warning: table not allowed L.' . __LINE__);
 		exit;
 	}
 
-	$db = DB::getDB();
-	$sql = "select `ID`, `TYPE`, `SIZE`, `IMAGE`, `WIDTH`, `HEIGHT`, UNIX_TIMESTAMP(`A_CREATE_DATE`) as A_CREATE_DATE
-		from `".DB_Image::conf_get_table_name()."`
-		where
-			`REMOTE_ID`='".$remote_id."'
-			and `REMOTE_TABLE`='".$remote_table."'
-		order by `ID` asc
-		limit 1 offset ".$number."
-	";
-
-	$res = $db->query($sql);
-	if (!$db->num_rows($res)) {
+	$image_row = DB_Image::getImage($remote_table, $remote_id, $number);
+	if (!$image_row) {
 		header('HTTP/1.1 400: Bad Request');
-		header('Warning: images not found in db L.' . __LINE__);
+		header('Warning: image not found in db L.' . __LINE__);
 		exit;
 	}
 
-	if ($image_row = $db->fetch( $res )) {
-		$etag = md5($image_row->ID . $image_row->A_CREATE_DATE);
-		if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $image_row->A_CREATE_DATE
-			|| trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
-			header("HTTP/1.1 304 Not Modified");
-			exit;
-		}
-		$expire_date = mktime(0, 0, 0, date('m') + 3, date('d'), date('Y'));
-
-		if ($image_resize) {
-			list($resize_w, $resize_h) = explode('x', $image_resize, 2);
-			$resize_w = intval($resize_w); $resize_h = intval($resize_h);
-			if ($resize_w > 0 && $resize_h > 0) {
-				$im = imagecreatefromstring( $image_row->IMAGE );
-				$image_resized = DB_Image::resize_image_from_data($im, $resize_w, $resize_h);
-
-				header("Content-type: ".$image_row->TYPE);
-				//header("Cache-control: public");
-				header("Cache-control: public");
-				header("Pragma: public");// default 'no-cache'
-				header("Etag: ".$etag);
-				header("Expires: " . gmdate("D, d M Y H:i:s", $expire_date) . " GMT");
-				header("Last-Modified: " . gmdate("D, d M Y H:i:s", $image_row->A_CREATE_DATE) . " GMT");
-				if ($image_row->TYPE == 'image/png') {
-					imagepng($image_resized);
-				} else if ($image_row->TYPE == 'image/jpeg' || $image_row->TYPE == 'image/jpg') {
-					imagejpeg($image_resized);
-				} else if ($image_row->TYPE == 'image/gif') {
-					imagegif($image_resized);
-				}
-			} else {
-				echo'ERROR wrong param resize (WxH)';
-			}
+	$etag = md5($image_row->ID . $image_row->A_CREATE_DATE_TS);
+	if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $image_row->A_CREATE_DATE_TS
+		|| trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
+		header("HTTP/1.1 304 Not Modified");
+		exit;
+	}
+	$expire_date = mktime(0, 0, 0, date('m') + 3, date('d'), date('Y'));
+
+	$maxWidth = 0;
+	$maxHeight = 0;
+	if ($imageResize) {
+		list($maxWidth, $maxHeight) = explode('x', $imageResize, 2);
+		$maxWidth = intval($maxWidth);
+		$maxHeight = intval($maxHeight);
+		if ($maxWidth <= 0 || $maxHeight <= 0) {
+			header('HTTP/1.1 400: Bad Request');
+			echo'ERROR wrong param resize (WxH)';
 			exit;
 		}
+	}
 
-		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($image_row);echo'</pre>';
-		//header("Content-type: ".$image_row->TYPE);
-		header("Content-type: ".$image_row->TYPE);
+	if (!$DBG) {
+		header("Content-type: {$image_row->TYPE}");
 		header("Cache-control: public");
 		header("Pragma: public");// default 'no-cache'
-		header("Etag: ".$etag);
-		header("Content-length: ".$image_row->SIZE);
+		header("Etag: {$etag}");
+		if (!$imageResize) {
+			header("Content-length: {$image_row->SIZE}");
+		}
 		header("Expires: " . gmdate("D, d M Y H:i:s", $expire_date) . " GMT");
-		header("Last-Modified: " . gmdate("D, d M Y H:i:s", $image_row->A_CREATE_DATE) . " GMT");
-		//echo stripslashes($image_row->IMAGE);
-		print $image_row->IMAGE;
-		//file_put_contents('/home/pl/projekty/kyoritsu.pl/src/1.jpg', $image_row->IMAGE);
+		header("Last-Modified: " . gmdate("D, d M Y H:i:s", $image_row->A_CREATE_DATE_TS) . " GMT");
+	}
+	if ($imageResize) {
+		print DB_Image::resizeImageFromBlob($image_row->IMAGE, $image_row->TYPE, $maxWidth, $maxHeight);
 	} else {
-		header('HTTP/1.1 400: Bad Request');
-		header('Warning: image not found in db L.' . __LINE__);
+		print $image_row->IMAGE;
 	}
 	exit;
 }

+ 44 - 98
SE/procesy5.php

@@ -38,6 +38,7 @@ Lib::loadClass('S');
 Lib::loadClass('ProcesHelper');
 Lib::loadClass('Tree');
 Lib::loadClass('TreeHelper');
+Lib::loadClass('DB_Image');
 Lib::loadClass('TreeSortChildren');
 
 //   ==========  Task functions  ==============
@@ -1337,104 +1338,71 @@ function fun_SHOW_EXTERNAL_IMAGE() {
 	$remote_table = V::get('tbl', '', $_REQUEST);
 	$remote_id = V::get('id', '', $_REQUEST, 'int');
 	$number = V::get('number', '', $_REQUEST, 'int');
-	$image_resize = V::get('resize', '', $_REQUEST);
+	$imageResize = V::get('resize', '', $_REQUEST);
+	$DBG = (V::get('DBG', 0, $_REQUEST, 'int') > 0);
 
-	Lib::loadClass('DB_Image');
-
-	// check remote id
 	if ($remote_id <= 0) {
 		header('HTTP/1.1 400: Bad Request');
 		header('Warning: wrong ID L.' . __LINE__);
 		exit;
 	}
 
-	// check remote table
-	$remote_tables = DB_Image::conf_get('remote_tables');
-	if (!in_array($remote_table, $remote_tables)) {
+	if (!DB_Image::tableIsAllowed($remote_table)) {
 		header('HTTP/1.1 400: Bad Request');
 		header('Warning: table not allowed L.' . __LINE__);
 		exit;
 	}
 
-	$db = DB::getDB();
-	$sql = "select `ID`, `TYPE`, `SIZE`, `IMAGE`, `WIDTH`, `HEIGHT`
-			, UNIX_TIMESTAMP(`A_CREATE_DATE`) as A_CREATE_DATE_TS
-		from `".DB_Image::conf_get_table_name()."`
-		where
-			`REMOTE_ID`='".$remote_id."'
-			and `REMOTE_TABLE`='".$remote_table."'
-		order by `ID` asc
-		limit 1 offset ".$number."
-	";
-
-	$res = $db->query($sql);
-	if (!$db->num_rows($res)) {
+	$image_row = DB_Image::getImage($remote_table, $remote_id, $number);
+	if (!$image_row) {
 		header('HTTP/1.1 400: Bad Request');
-		header('Warning: images not found in db L.' . __LINE__);
+		header('Warning: image not found in db L.' . __LINE__);
 		exit;
 	}
 
-	if ($image_row = $db->fetch( $res )) {
-		$etag = md5($image_row->ID . $image_row->A_CREATE_DATE_TS);
-		if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $image_row->A_CREATE_DATE_TS
-			|| trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
-			//header("HTTP/1.1 304 Not Modified");
-			//exit;
-		}
-		$expire_date = mktime(0, 0, 0, date('m') + 3, date('d'), date('Y'));
-
-		if ($image_resize) {
-			list($resize_w, $resize_h) = explode('x', $image_resize, 2);
-			$resize_w = intval($resize_w); $resize_h = intval($resize_h);
-			if ($resize_w > 0 && $resize_h > 0) {
-				$im = imagecreatefromstring( $image_row->IMAGE );
-				$image_resized = DB_Image::resize_image_from_data($im, $resize_w, $resize_h);
-
-				header("Content-type: ".$image_row->TYPE);
-				//header("Cache-control: public");
-				header("Cache-control: public");
-				header("Pragma: public");// default 'no-cache'
-				header("Etag: ".$etag);
-				header("Expires: " . gmdate("D, d M Y H:i:s", $expire_date) . " GMT");
-				header("Last-Modified: " . gmdate("D, d M Y H:i:s", $image_row->A_CREATE_DATE_TS) . " GMT");
-				
-				if(function_exists('imagepng')) {
-				if ($image_row->TYPE == 'image/png') {
-					imagepng($image_resized);
-				} else if ($image_row->TYPE == 'image/jpeg' || $image_row->TYPE == 'image/jpg') {
-					imagejpeg($image_resized);
-				} else if ($image_row->TYPE == 'image/gif') {
-					imagegif($image_resized);
-				}
-				} else echo $image_row->IMAGE;
-			} else {
-				echo'ERROR wrong param resize (WxH)';
-			}
+	$etag = md5($image_row->ID . $image_row->A_CREATE_DATE_TS);
+	if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $image_row->A_CREATE_DATE_TS
+		|| trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
+		//header("HTTP/1.1 304 Not Modified");
+		//exit;
+	}
+	$expire_date = mktime(0, 0, 0, date('m') + 3, date('d'), date('Y'));
+
+	$maxWidth = 0;
+	$maxHeight = 0;
+	if ($imageResize) {
+		list($maxWidth, $maxHeight) = explode('x', $imageResize, 2);
+		$maxWidth = intval($maxWidth);
+		$maxHeight = intval($maxHeight);
+		if ($maxWidth <= 0 || $maxHeight <= 0) {
+			header('HTTP/1.1 400: Bad Request');
+			echo'ERROR wrong param resize (WxH)';
 			exit;
 		}
+	}
 
-		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($image_row);echo'</pre>';
-		//header("Content-type: ".$image_row->TYPE);
-		header("Content-type: ".$image_row->TYPE);
+	if (!$DBG) {
+		header("Content-type: {$image_row->TYPE}");
 		header("Cache-control: public");
 		header("Pragma: public");// default 'no-cache'
-		header("Etag: ".$etag);
-		header("Content-length: ".$image_row->SIZE);
+		header("Etag: {$etag}");
+		if (!$imageResize) {
+			header("Content-length: {$image_row->SIZE}");
+		}
 		header("Expires: " . gmdate("D, d M Y H:i:s", $expire_date) . " GMT");
 		header("Last-Modified: " . gmdate("D, d M Y H:i:s", $image_row->A_CREATE_DATE_TS) . " GMT");
-		//echo stripslashes($image_row->IMAGE);
-		print $image_row->IMAGE;
-		//file_put_contents('/home/pl/projekty/kyoritsu.pl/src/1.jpg', $image_row->IMAGE);
+	}
+	if ($imageResize) {
+		print DB_Image::resizeImageFromBlob($image_row->IMAGE, $image_row->TYPE, $maxWidth, $maxHeight);
 	} else {
-		header('HTTP/1.1 400: Bad Request');
-		header('Warning: image not found in db L.' . __LINE__);
+		print $image_row->IMAGE;
 	}
 	exit;
 }
 
 
 function fun_SHOW_IMAGE() {
-	$image_id = V::get('image_id', '', $_REQUEST, 'int');
+	$image_id = V::get('image_id', 0, $_REQUEST, 'int');
 
 	if ($image_id <= 0) {
 		header('HTTP/1.1 400: Bad Request');
@@ -1442,31 +1410,23 @@ function fun_SHOW_IMAGE() {
 		exit;
 	}
 
-	Lib::loadClass('DB_Image');
-
-	$db = DB::getDB();
-	$image_row = DB::get_by_id( DB_Image::conf_get_table_name(), $image_id);
+	$image_row = DB_Image::getImageById($image_id);
 	if (!$image_row) {
 		header('HTTP/1.1 400: Bad Request');
 		header('Warning: image not found in db L.' . __LINE__);
 		exit;
 	}
 
-	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r($image_row);echo'</pre>';
-	//header("Content-type: ".$image_row->TYPE);
-	// TODO: header cache
 	header("Content-type: ".$image_row->TYPE);
 	header("Content-length: ".$image_row->SIZE);
-	//echo stripslashes($image_row->IMAGE);
 	print $image_row->IMAGE;
 	exit;
-	//file_put_contents('/home/pl/projekty/kyoritsu.pl/src/1.jpg', $image_row->IMAGE);
 }
 
 
 function fun_IMAGE_ADD() {
 	$remote_table = V::get('tbl', '', $_REQUEST);
-	$remote_id = V::get('id', '', $_REQUEST, 'int');
+	$remote_id = V::get('id', 0, $_REQUEST, 'int');
 	$task = V::get('task', '', $_REQUEST);
 
 	$thiss = new stdClass();
@@ -1474,8 +1434,6 @@ function fun_IMAGE_ADD() {
 	$errors = array();
 	$msgs = array();
 
-	Lib::loadClass('DB_Image');
-
 	// check remote id
 	if ($remote_id <= 0) {
 		echo'<p>';
@@ -1487,22 +1445,10 @@ function fun_IMAGE_ADD() {
 	}
 
 	// check remote table
-	$remote_tables = DB_Image::conf_get('remote_tables');
-	if (!in_array($remote_table, $remote_tables)) {
+	if (!DB_Image::tableIsAllowed($remote_table)) {
 		$errors[] = "Error table not allowed to add image";
 	}
 
-	if (0) {
-		if ($ARG1_VAL != 'DODAJ_PLIK') {
-			if ($_SESSION['CURRENT_MENU'] == $thiss->DETECT_EDIT_FUNCTION) {
-				if (strstr($_SESSION[$thiss->DETECT_TABLE_COLUMN]['PERMEDIT']['ITEM_IMAGE_REMOTE'],"W")) {
-					echo '<a target="_blank" href="'.$_SERVER['PHP_SELF']."?function_init=typespecial_ITEM_IMAGE_REMOTE&ARG1_VAL=DODAJ_PLIK&HEADER_NOT_INIT=YES".'">'."DODAJ_PLIK".'</a>';
-				}
-			}
-			return;
-		}
-	}
-
 	// task
 	$task = V::get('task', '', $_REQUEST);
 	if ($task == 'REMOVE') {// TODO: przerobic na funkcje, zwrocic msg, pokazac w body
@@ -1524,7 +1470,7 @@ function fun_IMAGE_ADD() {
 		}
 
 		if (empty($errors)) {
-			$affected = DB_Image::delete_image($req['ID'], $req['REMOTE_TABLE'], $req['REMOTE_ID']);
+			$affected = DB_Image::deleteImage($req['ID'], $req['REMOTE_TABLE'], $req['REMOTE_ID']);
 			if ($affected == 1) {
 				$msgs[] = '<p>'."Usunieto zdjecie ID=".$req['ID'].'</p>';
 			} else {
@@ -1538,7 +1484,7 @@ function fun_IMAGE_ADD() {
 		//echo '<p>Please select a file</p>';
 	}
 	else {
-		$errors = DB_Image::upload_image($remote_table, $remote_id, $_FILES['userfile']);
+		$errors = DB_Image::uploadImage($remote_table, $remote_id, $_FILES['userfile']);
 		// give praise and thanks to the php gods
 		if (empty($errors)) {
 			$msgs[] = '<p>Thank you for submitting</p>';
@@ -1579,7 +1525,7 @@ function fun_IMAGE_ADD() {
 		echo"Rodzaj obrazka: ";
 		echo'<input type="text" name="'."DEST".'" value="'."".'" />';
 		$select_arr = array();
-		$select_arr = DB_Image::conf_get_options( $thiss->DETECT_TABLE_NAME );
+		$select_arr = DB_Image::conf_get_options($thiss->DETECT_TABLE_NAME);
 
 		if (!empty($select_arr)) {
 			echo' ';
@@ -1600,7 +1546,7 @@ function fun_IMAGE_ADD() {
 
 
 // TODO: show images, mv to function {
-	$images = DB_Image::get_images($thiss->DETECT_TABLE_NAME, $remote_id);
+	$images = DB_Image::getImages($thiss->DETECT_TABLE_NAME, $remote_id);
 
 	echo'<div class="box box-blue" style="overflow:hidden">';
 	if (empty($images)) {
@@ -1624,7 +1570,7 @@ function fun_IMAGE_ADD() {
 					echo''.$r->NAME.'<br />';
 					echo''.$r->DEST.'<br />';
 					echo''.$r->A_CREATE_DATE.'<br />';
-					echo''.DB_Image::show_size($r->SIZE).' '.$r->WIDTH.'x'.$r->HEIGHT.'<br />';
+					echo''.DB_Image::showSize($r->SIZE).' '.$r->WIDTH.'x'.$r->HEIGHT.'<br />';
 					echo'<img src="'.$link_src.'" '.$st.'/>';
 				echo'</td>';
 			echo'</tr>';

+ 400 - 279
SE/se-lib/DB_Image.php

@@ -3,327 +3,448 @@
 
 class DB_Image {
 
-public static function conf_get( $key ) {
-	static $conf;
-	if (empty($conf)) {
-		$conf['table_name'] = 'CRM_IMAGE';
-		$conf['max_size'] = 1024 * 1024 * 16;// MAX for MEDIUMBLOB field
-		$conf['allowed_types'] = array();
-		$conf['allowed_types'][] = 'image/png';
-		$conf['allowed_types'][] = 'image/jpeg';
-		$conf['allowed_types'][] = 'image/gif';
-
-		$conf['remote_tables'] = array();
-		$conf['remote_tables'][] = 'CRM_LISTA_ZASOBOW';
-		$conf['remote_tables'][] = 'CRM_PROCES';
-		$conf['remote_tables'][] = 'CRM_WSKAZNIK';
-
-		$conf['desc_options'] = array();
-		$conf['desc_options']['CRM_LISTA_ZASOBOW'] = array();
-		$conf['desc_options']['CRM_PROCES'] = array();
-		$conf['desc_options']['CRM_WSKAZNIK'] = array();
-
-		$conf['desc_options_conf'] = array();
-		$conf['desc_options_conf']['CRM_LISTA_ZASOBOW'] = array();
-		$conf['desc_options_conf']['CRM_PROCES'] = array();
-		$conf['desc_options_conf']['CRM_WSKAZNIK'] = array();
-
-		$options = array();
-		$options['screenshot'] = "screenshot (800x600)";
-		$options['icon'] = "icon (16x16)";
-
-		$conf['desc_options']['CRM_LISTA_ZASOBOW'] = $options;
-		$conf['desc_options']['CRM_PROCES'] = $options;
-		$conf['desc_options']['CRM_WSKAZNIK'] = $options;
-
-		$desc_options_conf = array();
-		$desc_options_conf['screenshot']['max_width'] = 800;
-		$desc_options_conf['screenshot']['max_height'] = 600;
-		$desc_options_conf['icon']['max_width'] = 16;
-		$desc_options_conf['icon']['max_height'] = 16;
-
-		$conf['desc_options_conf']['CRM_LISTA_ZASOBOW'] = $desc_options_conf;
-		$conf['desc_options_conf']['CRM_PROCES'] = $desc_options_conf;
-		$conf['desc_options_conf']['CRM_WSKAZNIK'] = $desc_options_conf;
+	public static function calculateThumbImageSize($width, $height, $maxWidth, $maxHeight) {
+		$width     = intval($width);
+		$height    = intval($height);
+		$maxWidth  = intval($maxWidth);
+		$maxHeight = intval($maxHeight);
+		if ($width <= 0 || $height <= 0 || $maxWidth <= 0 || $maxHeight <= 0) {
+			throw new Exception("Wrong params");
+		}
+		list($newWidth, $newHeight) = array($width, $height);
+
+		if ($width >= $maxWidth || $height >= $maxWidth) {
+			$ratioWidth  = $maxWidth  / $width;
+			$ratioHeight = $maxHeight / $height;
+
+			if ($ratioWidth > $ratioHeight) {
+				$ratio = $ratioHeight;
+			} else {
+				$ratio = $ratioWidth;
+			}
+
+			$newWidth  = intval($width  * $ratio);
+			$newHeight = intval($height * $ratio);
+		}
+		return array($newWidth, $newHeight);
 	}
-	if (array_key_exists($key, $conf)) {
-		return $conf[ $key ];
+
+	public static function resizeImageFromBlob($imageBlob, $type, $maxWidth, $maxHeight) {
+		$resizedImageBlob = null;
+		list($w, $h) = self::getImageGeometryFromBlob($imageBlob);
+		list($newWidth, $newHeight) = self::calculateThumbImageSize($w, $h, $maxWidth, $maxHeight);
+		if ($newW == $w && $newH == $h) {
+			return $imageBlob;
+		}
+
+		if (class_exists('Imagick')) {
+			$im = new Imagick();
+			$im->readImageBlob($imageBlob);
+			$im->thumbnailImage($newWidth, $newHeight, true);
+			$resizedImageBlob = $im->getImageBlob();
+		} else {
+			$im = imagecreatefromstring($imageBlob);
+			$image_resized = self::resize_image_from_data($im, $newWidth, $newHeight);
+			ob_start();
+			if ($type == 'image/png') {
+				imagepng($image_resized);
+			} else if ($type == 'image/jpeg' || $type == 'image/jpg') {
+				imagejpeg($image_resized);
+			} else if ($type == 'image/gif') {
+				imagegif($image_resized);
+			}
+			$resizedImageBlob = ob_get_contents();
+			ob_clean();
+		}
+		return $resizedImageBlob;
 	}
-	return null;
-}
 
-public static function conf_get_table_name() {
-	return self::conf_get('table_name');
-}
+	public static function getImageGeometryFromBlob($imageBlob) {
+		if (class_exists('Imagick')) {
+			$im = new Imagick();
+			$im->readImageBlob($imageBlob);
+			$geometry = $im->getImageGeometry();
+			$w = $geometry['width'];
+			$h = $geometry['height'];
+		} else {
+			$im = imagecreatefromstring($imageBlob);
+			$w = imagesx($im);
+			$h = imagesy($im);
+		}
+		return array($w, $h);
+	}
 
-/*
- * Get options for table.
- */
-public static function conf_get_options( $table ) {
-	$ret = array();
-	$arr = self::conf_get('desc_options');
-	if (array_key_exists($table, $arr)) {
-		return $arr[$table];
+	public static function getImage($remote_table, $remote_id, $number = 0) {
+		$db = DB::getDB();
+		$sql = "select `ID`, `TYPE`, `SIZE`, `IMAGE`, `WIDTH`, `HEIGHT`
+				, UNIX_TIMESTAMP(`A_CREATE_DATE`) as A_CREATE_DATE_TS
+			from `".self::conf_get_table_name()."`
+			where
+				`REMOTE_ID`='{$remote_id}'
+				and `REMOTE_TABLE`='{$remote_table}'
+			order by `ID` asc
+			limit 1 offset {$number}
+		";
+
+		$res = $db->query($sql);
+		if (!$db->num_rows($res)) {
+			return null;
+		}
+		return $db->fetch($res);
 	}
-	return $ret;
-}
 
-/*
- * Get config for all options.
- */
-public static function conf_get_options_conf( $table ) {
-	$ret = array();
-	$arr = self::conf_get('desc_options_conf');
-	if (array_key_exists($table, $arr)) {
-		return $arr[$table];
+	public static function getImageById($imageId) {
+		$db = DB::getDB();
+		$sql = "select `ID`, `TYPE`, `SIZE`, `IMAGE`, `WIDTH`, `HEIGHT`
+				, UNIX_TIMESTAMP(`A_CREATE_DATE`) as A_CREATE_DATE_TS
+			from `".self::conf_get_table_name()."`
+			where
+				`ID`='{$imageId}'
+		";
+
+		$res = $db->query($sql);
+		return $db->fetch($res);
+	}
+
+	public static function tableIsAllowed($remote_table) {
+		$remote_tables = self::conf_get('remote_tables');
+		return in_array($remote_table, $remote_tables);
 	}
-	return $ret;
-}
 
-/*
- * Get config for selected option.
- */
-public static function conf_get_option_conf( $table, $key ) {
-	$ret = array();
-	$arr = self::conf_get('desc_options_conf');
-	if (array_key_exists($table, $arr)) {
-		if (array_key_exists($key, $arr[$table])) {
-			return $arr[$table][$key];
+	public static function conf_get($key) {
+		static $conf;
+		if (empty($conf)) {
+			$conf['table_name'] = 'CRM_IMAGE';
+			$conf['max_size'] = 1024 * 1024 * 16;// MAX for MEDIUMBLOB field
+			$conf['allowed_types'] = array();
+			$conf['allowed_types'][] = 'image/png';
+			$conf['allowed_types'][] = 'image/jpeg';
+			$conf['allowed_types'][] = 'image/gif';
+
+			$conf['remote_tables'] = array();
+			$conf['remote_tables'][] = 'CRM_LISTA_ZASOBOW';
+			$conf['remote_tables'][] = 'CRM_PROCES';
+			$conf['remote_tables'][] = 'CRM_WSKAZNIK';
+
+			$conf['desc_options'] = array();
+			$conf['desc_options']['CRM_LISTA_ZASOBOW'] = array();
+			$conf['desc_options']['CRM_PROCES'] = array();
+			$conf['desc_options']['CRM_WSKAZNIK'] = array();
+
+			$conf['desc_options_conf'] = array();
+			$conf['desc_options_conf']['CRM_LISTA_ZASOBOW'] = array();
+			$conf['desc_options_conf']['CRM_PROCES'] = array();
+			$conf['desc_options_conf']['CRM_WSKAZNIK'] = array();
+
+			$options = array();
+			$options['screenshot'] = "screenshot (800x600)";
+			$options['icon'] = "icon (16x16)";
+
+			$conf['desc_options']['CRM_LISTA_ZASOBOW'] = $options;
+			$conf['desc_options']['CRM_PROCES'] = $options;
+			$conf['desc_options']['CRM_WSKAZNIK'] = $options;
+
+			$desc_options_conf = array();
+			$desc_options_conf['screenshot']['max_width'] = 800;
+			$desc_options_conf['screenshot']['max_height'] = 600;
+			$desc_options_conf['icon']['max_width'] = 16;
+			$desc_options_conf['icon']['max_height'] = 16;
+
+			$conf['desc_options_conf']['CRM_LISTA_ZASOBOW'] = $desc_options_conf;
+			$conf['desc_options_conf']['CRM_PROCES'] = $desc_options_conf;
+			$conf['desc_options_conf']['CRM_WSKAZNIK'] = $desc_options_conf;
+		}
+		if (array_key_exists($key, $conf)) {
+			return $conf[$key];
 		}
+		return null;
 	}
-	return $ret;
-}
 
-public static function is_allowed_type( $type ) {
-	$allowed_types = self::conf_get('allowed_types');
-	if (in_array($type, $allowed_types)) {
-		return true;
+	public static function conf_get_table_name() {// TODO: RM Legacy
+		return self::getStorageTableName();
 	}
-	return false;
-}
 
-public static function read_image_data( $file, $mime_type ){
-	$im = null;
-	if ($mime_type == 'image/jpeg') {
-		$im = imagecreatefromjpeg( $file );
-	} else if ($mime_type == 'image/png') {
-		$im = imagecreatefrompng( $file );
-	} else if ($mime_type == 'image/gif') {
-		$im = imagecreatefromgif( $file );
+	public static function getStorageTableName() {
+		return self::conf_get('table_name');
 	}
-	return $im;
-}
 
-public static function get_images($remote_table, $remote_id) {
-	$db = DB::getDB();
-	$images = array();
-	$sql = "select
-			t.`ID`, t.`NAME`, t.`SIZE`, t.`TYPE`, t.`WIDTH`, t.`HEIGHT`
-			, t.`DEST`, t.`A_CREATE_DATE`
-			, t.`REMOTE_TABLE`, t.`REMOTE_ID`
-			, UNIX_TIMESTAMP(`A_CREATE_DATE`) as A_CREATE_DATE_TS
-		from `".self::conf_get_table_name()."` as t
-		where
-			t.`REMOTE_TABLE`='".$remote_table."'
-			and t.`REMOTE_ID`='".$remote_id."'
-	";
-	$res = $db->query($sql);
-	while ($r = $db->fetch( $res )) {
-		$images[] = $r;
+	public static function conf_get_options($table) {// TODO: RM Legacy
+		return self::getTableConfig($table);
 	}
-	return $images;
-}
 
-/**
- * Try to upload image to DB.
- * @returns Array of errors
- */
-public static function upload_image($remote_table, $remote_id, $req_file_data) {
-	$errors = array();
-	$maxsize = self::conf_get('max_size');
-
-	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$_FILES = ';print_r($_FILES);echo'</pre>';
-
-	if (is_uploaded_file($req_file_data['tmp_name'])) {
-		// check the file is less than the maximum file size
-		if ($req_file_data['size'] < $maxsize) {
-			// prepare the image for insertion
-			//$imgData = mysql_real_escape_string(file_get_contents($req_file_data['tmp_name']), $conn);// nie dziala mysql_real_escape_string
-			$fp = fopen($req_file_data['tmp_name'], 'r');
-			$imgData = fread($fp, filesize($req_file_data['tmp_name']));
-			$imgData = addslashes($imgData);
-			fclose($fp);
-
-			// get the image info..
-			$size = getimagesize($req_file_data['tmp_name']);
-
-			$obj = array();
-			$obj['DEST'] = (isset($_REQUEST['DEST']))? $_REQUEST['DEST'] : '';
-			$obj['TYPE'] = $size['mime'];
-			$obj['IMAGE'] = $imgData;
-			$obj['WIDTH'] = $size[0];
-			$obj['HEIGHT'] = $size[1];
-			$obj['NAME'] = $req_file_data['name'];
-			$obj['SIZE'] = $req_file_data['size'];
-			$obj['REMOTE_TABLE'] = $remote_table;
-			$obj['REMOTE_ID'] = $remote_id;
-
-			// check if type is allowed to upload
-			if (!DB_Image::is_allowed_type($obj['TYPE'])) {
-				$errors[] = 'File type "'.$obj['TYPE'].'" is not allowed.';
-				return $errors;
-			}
+	public static function getTableConfig($table) {
+		$ret = array();
+		$arr = self::conf_get('desc_options');
+		if (array_key_exists($table, $arr)) {
+			return $arr[$table];
+		}
+		return $ret;
+	}
 
-			// convert image if selected option
-			if ($obj['DEST']) {
-				$options_conf = DB_Image::conf_get_option_conf( $remote_table, $obj['DEST'] );
-				if (!empty($options_conf)) {
-					$max_width = 0;
-					$max_height = 0;
-					if (isset($options_conf['max_height']) && $obj['HEIGHT'] > $options_conf['max_height']) {
-						$max_height = $options_conf['max_height'];
-					}
-					if (isset($options_conf['max_width']) && $obj['WIDTH'] > $options_conf['max_width']) {
-						$max_width = $options_conf['max_width'];
-					}
-					if ($max_height || $max_width) {
-						//$img = DB_Image::resize_image($req_file_data['tmp_name'], $max_width, $max_height);
-						//open image, from file to data
-
-						// read data
-						$im = DB_Image::read_image_data($req_file_data['tmp_name'], $obj['TYPE']);
-						// resize image
-						$im = DB_Image::resize_image_from_data($im, $max_width, $max_height);
-						ob_start();
-							imagejpeg($im);
-						$obj['IMAGE'] = ob_get_clean();
-
-						$obj['SIZE'] = strlen($obj['IMAGE']);
-						$obj['IMAGE'] = addslashes($obj['IMAGE']);
-						$obj['WIDTH'] = imagesx($im);
-						$obj['HEIGHT'] = imagesy($im);
-					}
-				}
+	public static function conf_get_options_conf($table) {// TODO: RM Not used ?
+		$ret = array();
+		$arr = self::conf_get('desc_options_conf');
+		if (array_key_exists($table, $arr)) {
+			return $arr[$table];
+		}
+		return $ret;
+	}
+
+	public static function conf_get_option_conf($table, $key) {// TODO: used only in upload_image
+		$ret = array();
+		$arr = self::conf_get('desc_options_conf');
+		if (array_key_exists($table, $arr)) {
+			if (array_key_exists($key, $arr[$table])) {
+				return $arr[$table][$key];
 			}
+		}
+		return $ret;
+	}
 
-			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">size = ';print_r($size);echo'</pre>';
+	public static function is_allowed_type($type) {// TODO: used only in upload_image
+		$allowed_types = self::conf_get('allowed_types');
+		if (in_array($type, $allowed_types)) {
+			return true;
+		}
+		return false;
+	}
 
-			$sql_arr = array();
-			foreach ($obj as $key => $val) {
-				$sql_arr["`".$key."`"] = "'".$val."'";
+	public static function readImageBlobFromFile($file, $mimeType) {
+		$imBlob = null;
+		if (class_exists('Imagick')) {
+			$im = new Imagick($file);
+			$imBlob = $im->getImageBlob();
+		} else {
+			if ($mimeType == 'image/jpeg') {
+				$im = imagecreatefromjpeg($file);
+			} else if ($mimeType == 'image/png') {
+				$im = imagecreatefrompng($file);
+			} else if ($mimeType == 'image/gif') {
+				$im = imagecreatefromgif($file);
 			}
-			$sql = "insert into `".self::conf_get_table_name()."` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr)).") ; ";
+			ob_start();
+			if ($mimeType == 'image/png') {
+				imagepng($im);
+			} else if ($mimeType == 'image/jpeg' || $mimeType == 'image/jpg') {
+				imagejpeg($im);
+			} else if ($mimeType == 'image/gif') {
+				imagegif($im);
+			}
+			$imBlob = ob_get_contents();
+			ob_clean();
+		}
+		return $imBlob;
+	}
 
-			// insert the image
-			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">sql = ';print_r($sql);echo'</pre>';
-			$db = DB::getDB();
+	public static function read_image_data($file, $mime_type) {// TODO: used only in upload_image
+		$im = null;
+		if ($mime_type == 'image/jpeg') {
+			$im = imagecreatefromjpeg($file);
+		} else if ($mime_type == 'image/png') {
+			$im = imagecreatefrompng($file);
+		} else if ($mime_type == 'image/gif') {
+			$im = imagecreatefromgif($file);
+		}
+		return $im;
+	}
 
-			if (!$db->query($sql)) {
-				$errors[] = 'Unable to upload file - sql error';
-				//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">mysql err: '.mysql_errno($conn);var_dump(mysql_error($conn));echo'</pre>';
-				//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">sql: ';print_r($sql);echo'</pre>';
-			}
+	public static function get_images($remote_table, $remote_id) {// TODO: RM Legacy
+		return self::getImages($remote_table, $remote_id);
+	}
 
-			self::update_remote_table_stat( $remote_table, $remote_id );
+	public static function getImages($remote_table, $remote_id) {
+		$db = DB::getDB();
+		$images = array();
+		$sql = "select
+				t.`ID`, t.`NAME`, t.`SIZE`, t.`TYPE`, t.`WIDTH`, t.`HEIGHT`
+				, t.`DEST`, t.`A_CREATE_DATE`
+				, t.`REMOTE_TABLE`, t.`REMOTE_ID`
+				, UNIX_TIMESTAMP(`A_CREATE_DATE`) as A_CREATE_DATE_TS
+			from `".self::conf_get_table_name()."` as t
+			where
+				t.`REMOTE_TABLE`='{$remote_table}'
+				and t.`REMOTE_ID`='{$remote_id}'
+		";
+		$res = $db->query($sql);
+		while ($r = $db->fetch($res)) {
+			$images[] = $r;
 		}
+		return $images;
 	}
-	else {
-		// if the file is not less than the maximum allowed, print an error
-		$errors[] = 'File exceeds the Maximum File limit';
+
+	/**
+	 * Try to upload image to DB.
+	 * @returns Array of errors
+	 */
+	public static function upload_image($remote_table, $remote_id, $req_file_data) {// TODO: RM -> moved to uploadImage
+		return self::uploadImage($remote_table, $remote_id, $req_file_data);
 	}
-	return $errors;
-}
 
-public static function delete_image($id, $remote_table, $remote_id) {
-	$db = DB::getDB();
-	$sql = "delete from `".self::conf_get_table_name()."`
-		where
-			`ID`='".$id."'
-			and `REMOTE_ID`='".$remote_id."'
-			and `REMOTE_TABLE`='".$remote_table."'
-		limit 1
-	";
-	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">sql delete = ';print_r($sql);echo'</pre>';
-	$db->query( $sql );
-	$affected = $db->affected_rows();
-
-	self::update_remote_table_stat( $remote_table, $remote_id );
-
-	return $affected;
-}
+	public static function uploadImage($remote_table, $remote_id, $req_file_data) {
+		$errors = array();
+		$maxsize = self::conf_get('max_size');
+
+		if (is_uploaded_file($req_file_data['tmp_name'])) {
+			if ($req_file_data['size'] < $maxsize) {
+				$fp = fopen($req_file_data['tmp_name'], 'r');
+				$imgData = fread($fp, filesize($req_file_data['tmp_name']));
+				$imgData = addslashes($imgData);
+				fclose($fp);
+
+				$size = getimagesize($req_file_data['tmp_name']);
+
+				$sqlObj = array();
+				$sqlObj['DEST'] = (isset($_REQUEST['DEST']))? $_REQUEST['DEST'] : '';
+				$sqlObj['TYPE'] = $size['mime'];
+				$sqlObj['IMAGE'] = $imgData;
+				$sqlObj['WIDTH'] = $size[0];
+				$sqlObj['HEIGHT'] = $size[1];
+				$sqlObj['NAME'] = $req_file_data['name'];
+				$sqlObj['SIZE'] = $req_file_data['size'];
+				$sqlObj['REMOTE_TABLE'] = $remote_table;
+				$sqlObj['REMOTE_ID'] = $remote_id;
+
+				// check if type is allowed to upload
+				if (!self::is_allowed_type($sqlObj['TYPE'])) {
+					$errors[] = 'File type "'.$sqlObj['TYPE'].'" is not allowed.';
+					return $errors;
+				}
 
-/**
- * Updates field ITEM_IMAGE_REMOTE in remote table.
- * TODO: check if field exists!
- */
-public static function update_remote_table_stat($remote_table, $remote_id) {
-	// update stat `ITEM_IMAGE_REMOTE`
-	$sql = "update `".$remote_table."`
-			set `A_HAS_IMAGE`=(
-				select count(1)
-				from `".self::conf_get('table_name')."`
-				where
-					`REMOTE_ID`='".$remote_id."'
-					and `REMOTE_TABLE`='".$remote_table."'
-			)
-		where `ID`='".$remote_id."'
-		limit 1;
-	";
-	$db = DB::getDB();
-	$res = $db->query( $sql );
-	$affected = $db->affected_rows();
-}
+				// convert image if selected option
+				if ($sqlObj['DEST']) {
+					$options_conf = self::conf_get_option_conf($remote_table, $sqlObj['DEST']);
+					if (!empty($options_conf)) {
+						$max_width  = V::get('max_width',  0, $options_conf, 'int');
+						$max_height = V::get('max_height', 0, $options_conf, 'int');
+						if ($max_height > 0 && $max_width > 0) {
+							$imBlob = self::readImageBlobFromFile($req_file_data['tmp_name'], $sqlObj['TYPE']);
+							$sqlObj['IMAGE'] = self::resizeImageFromBlob($imBlob, $sqlObj['TYPE'], $max_width, $max_height);
+							list($sqlObj['WIDTH'], $sqlObj['HEIGHT']) = self::getImageGeometryFromBlob($sqlObj['IMAGE']);
+							$sqlObj['SIZE'] = strlen($sqlObj['IMAGE']);
+							$sqlObj['IMAGE'] = addslashes($sqlObj['IMAGE']);
+						}
+					}
+				}
 
-public static function resize_image($file, $w, $h, $crop=FALSE) {
-	// TODO: image type
-	$im = imagecreatefromjpeg($file);
-	return self::resize_image_from_data($im, $w, $h, $crop);
-}
+				$sql_arr = array();
+				foreach ($sqlObj as $key => $val) {
+					$sql_arr["`{$key}`"] = "'{$val}'";
+				}
+				$sql = "insert into `".self::conf_get_table_name()."` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr)).") ; ";
 
-public static function resize_image_from_data($im, $w, $h, $crop=FALSE) {
-	if ($w == 0) $w = $h;
-	if ($h == 0) $h = $w;
-	$width = imagesx($im);
-	$height = imagesy($im);
+				$db = DB::getDB();
+				if (!$db->query($sql)) {
+					$errors[] = 'Unable to upload file - sql error';
+				}
 
-	if ($width < $w && $height < $h) {
-		return $im;
+				self::update_remote_table_stat($remote_table, $remote_id);
+			}
+		}
+		else {
+			// if the file is not less than the maximum allowed, print an error
+			$errors[] = 'File exceeds the Maximum File limit';
+		}
+		return $errors;
 	}
 
-	$r = $width / $height;
-	if ($crop) {
-		if ($width > $height) {
-			$width = ceil($width-($width*($r-$w/$h)));
-		} else {
-			$height = ceil($height-($height*($r-$w/$h)));
+	public static function delete_image($id, $remote_table, $remote_id) {// TODO: RM Legacy
+		return self::deleteImage($id, $remote_table, $remote_id);
+	}
+
+	public static function deleteImage($id, $remote_table, $remote_id) {
+		$db = DB::getDB();
+		$sql = "delete from `".self::conf_get_table_name()."`
+			where
+				`ID`='{$id}'
+				and `REMOTE_ID`='{$remote_id}'
+				and `REMOTE_TABLE`='{$remote_table}'
+			limit 1
+		";
+		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">sql delete = ';print_r($sql);echo'</pre>';
+		$db->query($sql);
+		$affected = $db->affected_rows();
+
+		self::update_remote_table_stat($remote_table, $remote_id);
+
+		return $affected;
+	}
+
+	/**
+	 * Updates field ITEM_IMAGE_REMOTE in remote table.
+	 * TODO: check if field exists!
+	 */
+	public static function update_remote_table_stat($remote_table, $remote_id) {// TODO: used only in this file
+		// update stat `ITEM_IMAGE_REMOTE`
+		$sql = "update `{$remote_table}`
+				set `A_HAS_IMAGE`=(
+					select count(1)
+					from `".self::conf_get('table_name')."`
+					where
+						`REMOTE_ID`='{$remote_id}'
+						and `REMOTE_TABLE`='{$remote_table}'
+				)
+			where `ID`='{$remote_id}'
+			limit 1;
+		";
+		$db = DB::getDB();
+		$res = $db->query($sql);
+		$affected = $db->affected_rows();
+	}
+
+	public static function resize_image($file, $w, $h, $crop = FALSE) {
+		// TODO: image type
+		$im = imagecreatefromjpeg($file);
+		return self::resize_image_from_data($im, $w, $h, $crop);
+	}
+
+	public static function resize_image_from_data($im, $w, $h, $crop = FALSE) {
+		if ($w == 0) $w = $h;
+		if ($h == 0) $h = $w;
+		$width = imagesx($im);
+		$height = imagesy($im);
+
+		if ($width < $w && $height < $h) {
+			return $im;
 		}
-		$newwidth = $w;
-		$newheight = $h;
-	} else {
-		if ($w/$h > $r) {
-			$newwidth = $h*$r;
+
+		$r = $width / $height;
+		if ($crop) {
+			if ($width > $height) {
+				$width = ceil($width-($width*($r-$w/$h)));
+			} else {
+				$height = ceil($height-($height*($r-$w/$h)));
+			}
+			$newwidth = $w;
 			$newheight = $h;
 		} else {
-			$newheight = $w/$r;
-			$newwidth = $w;
+			if ($w/$h > $r) {
+				$newwidth = $h*$r;
+				$newheight = $h;
+			} else {
+				$newheight = $w/$r;
+				$newwidth = $w;
+			}
 		}
+		$dst = imagecreatetruecolor($newwidth, $newheight);
+		imagecopyresampled($dst, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
+
+		return $dst;
 	}
-	$dst = imagecreatetruecolor($newwidth, $newheight);
-	imagecopyresampled($dst, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
 
-	return $dst;
-}
+	public static function show_size($size) {// TODO: RM -> moved to showSize
+		return self::showSize($size);
+	}
 
-public static function show_size( $size ) {
-	$ret_unit = 'B';
-	if ($size > 1024 * 1024) {
-		$size = $size / (1024 * 1024);
-		$ret_unit = 'MB';
-	} else if ($size > 1024) {
-		$size = $size / 1024;
-		$ret_unit = 'KB';
+	public static function showSize($size) {
+		$ret_unit = 'B';
+		if ($size > 1024 * 1024) {
+			$size = $size / (1024 * 1024);
+			$ret_unit = 'MB';
+		} else if ($size > 1024) {
+			$size = $size / 1024;
+			$ret_unit = 'KB';
+		}
+		return number_format($size, 2, '.', ' ').''.$ret_unit;
 	}
-	return number_format($size, 2, '.', ' ').''.$ret_unit;
-}
 
 }