Related
I have that free php code-function (of Pedro Pinheiro https://github.com/pedroppinheiro)
function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
list($original_width, $original_height, $original_type) = getimagesize($filepath);
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
// figuring out the color for the background
if(is_array($background) && count($background) === 3) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($background === 'transparent' && $original_type === 3) {
imagesavealpha($new_image, TRUE);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}`
it creates thumbnails from single image file when you call function like this
$success = createThumbnail(__DIR__.DIRECTORY_SEPARATOR.'image.jpg', __DIR__.DIRECTORY_SEPARATOR.'image_thumb.jpg', 60, 60, array(255,255,255));
It is okay for single image file but I want it to convert all images in a folder what should I do? When I use for each it does not work.
I am trying to develop a joomla module I have that code that grabbing images
static function getList($params) {
$filter = '\.png$|\.gif$|\.jpg$|\.bmp$';
$path = $params->get('path');
$files = JFolder::files(JPATH_BASE.$path,$filter);
$i=0;
$lists = array();
foreach ($files as $file) {
$lists[$i]['title'] = JFile::stripExt($file);
$lists[$i]['image'] = JURI::base().str_replace(DS,'/',substr($path,1)).'/'.$file;
$i++;
}
return $lists;
}
Then I add this to create thumbnails
<?php
$filepath=JUri::root() . '/images/';
$thumbpath=JUri::root() . '/images/thumbs/';
$success=createThumbnail($filepath, $thumbpath, 160, 160, array(0,0,0));
?>
<?php foreach ($lists as $item):?>
<div>
<?php echo $success;?>
</div>
<?php endforeach; ?>
But it fails. thanks in advance.
i have two type of image upload :
first high resolution :
$specialImages = count($_FILES['specialImg']['name']);
$specialMinwidth = 3000;
$specialMinheight = 2500;
$urlSpecialImages = array();
if ($specialImages) {
for ($i=1; $i<=$specialImages; $i++) {
if ($_FILES['specialImg']['name'][$i] != "") {
if ((($_FILES['specialImg']['type'][$i] == "image/pjpeg") ||
($_FILES['specialImg']['type'][$i] == "image/jpeg") ||
($_FILES['specialImg']['type'][$i] == "image/png")) &&
($_FILES['specialImg']['size'][$i] < $this->return_bytes(ini_get('post_max_size')))) {
list($width, $height, $type, $attr) = getimagesize($_FILES['specialImg']['tmp_name'][$i]);
if ($width >= $specialMinwidth && $height >= $specialMinheight) {
$urlSpecialImages[$i] = $_FILES['specialImg']['tmp_name'][$i];
}
else {
$this->errors[] = $this->module->l("L'image doit ĂȘtre au format minimum de 3000px x 2500px", 'addproduct');
}
second low resolution :
$images = count($_FILES['images']['name']);
$minwidth = 1500;
$minheight = 1500;
if ($images <= Configuration::get('JMARKETPLACE_MAX_IMAGES')) {
for ($i=1; $i<=Configuration::get('JMARKETPLACE_MAX_IMAGES'); $i++) {
if ($_FILES['images']['name'][$i] != "") {
if ((($_FILES['images']['type'][$i] == "image/pjpeg") ||
($_FILES['images']['type'][$i] == "image/jpeg") ||
($_FILES['images']['type'][$i] == "image/png")) &&
($_FILES['images']['size'][$i] < $this->return_bytes(ini_get('post_max_size')))) {
list($width, $height, $type, $attr) = getimagesize($_FILES['images']['tmp_name'][$i]);
if ($width == $minwidth && $height == $minheight) {
$url_images[$i] = $_FILES['images']['tmp_name'][$i];
}
else {
$this->errors[] = $this->module->l('The image format need to be 1500 x 1500 pixels', 'addproduct');
}
i want to use the special $specialImages uploaded and resize them to . 1500x1500 on images low resolution !
because i want to get both resolution by one upload ! how can i do that ?
Image resize function example:
function resizeImage($file = 'image.png', $maxwidth = 1366){
error_reporting(0);
$image_info = getimagesize($file);
$image_width = $image_info[0];
$image_height = $image_info[1];
$ratio = $image_width / $maxwidth;
$info = getimagesize($file);
if ($image_width > $maxwidth) {
// GoGoGo
$newwidth = $maxwidth;
$newheight = (int)($image_height / $ratio);
if ($info['mime'] == 'image/jpeg') {
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
echo imagejpeg($thumb,$file,90);
}
if ($info['mime'] == 'image/jpg') {
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
echo imagejpeg($thumb,$file,90);
}
if ($info['mime'] == 'image/png') {
$im = imagecreatefrompng($file);
$im_dest = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($im_dest, false);
imagecopyresampled($im_dest, $im, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
imagesavealpha($im_dest, true);
imagepng($im_dest, $file, 9);
}
if ($info['mime'] == 'image/gif') {
$im = imagecreatefromgif($file);
$im_dest = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($im_dest, false);
imagecopyresampled($im_dest, $im, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
imagesavealpha($im_dest, true);
imagegif($im_dest, $file);
}
}}
Use:
resizeImage('D:\tmp\11.png', 1366);
I'm using the newest version of Prestashop (1.6.1.5), and I've got some problems with quality of product images.
While resizing (creating thumbnails like large_default, home_default etc) grey stripes appears on destination image.
I followed prestashop code and noticed that it happens after imagecopyresized() function, I tried to replace it with imagecopyresampled() but it doesn't help much.
Here is a link to the original image http://postimg.org/image/ib42bh81t, and here is a link to resized one (the one with grey stripes) http://postimg.org/image/i3tpda7sx
Prestashop resize() method:
public static function resize($src_file, $dst_file, $dst_width = null, $dst_height = null, $file_type = 'jpg',
$force_type = false, &$error = 0, &$tgt_width = null, &$tgt_height = null, $quality = 5,
&$src_width = null, &$src_height = null)
{
if (PHP_VERSION_ID < 50300) {
clearstatcache();
} else {
clearstatcache(true, $src_file);
}
if (!file_exists($src_file) || !filesize($src_file)) {
return !($error = self::ERROR_FILE_NOT_EXIST);
}
list($tmp_width, $tmp_height, $type) = getimagesize($src_file);
$rotate = 0;
if (function_exists('exif_read_data') && function_exists('mb_strtolower')) {
$exif = #exif_read_data($src_file);
if ($exif && isset($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$src_width = $tmp_width;
$src_height = $tmp_height;
$rotate = 180;
break;
case 6:
$src_width = $tmp_height;
$src_height = $tmp_width;
$rotate = -90;
break;
case 8:
$src_width = $tmp_height;
$src_height = $tmp_width;
$rotate = 90;
break;
default:
$src_width = $tmp_width;
$src_height = $tmp_height;
}
} else {
$src_width = $tmp_width;
$src_height = $tmp_height;
}
} else {
$src_width = $tmp_width;
$src_height = $tmp_height;
}
// If PS_IMAGE_QUALITY is activated, the generated image will be a PNG with .jpg as a file extension.
// This allow for higher quality and for transparency. JPG source files will also benefit from a higher quality
// because JPG reencoding by GD, even with max quality setting, degrades the image.
if (Configuration::get('PS_IMAGE_QUALITY') == 'png_all'
|| (Configuration::get('PS_IMAGE_QUALITY') == 'png' && $type == IMAGETYPE_PNG) && !$force_type) {
$file_type = 'png';
}
if (!$src_width) {
return !($error = self::ERROR_FILE_WIDTH);
}
if (!$dst_width) {
$dst_width = $src_width;
}
if (!$dst_height) {
$dst_height = $src_height;
}
$width_diff = $dst_width / $src_width;
$height_diff = $dst_height / $src_height;
$ps_image_generation_method = Configuration::get('PS_IMAGE_GENERATION_METHOD');
if ($width_diff > 1 && $height_diff > 1) {
$next_width = $src_width;
$next_height = $src_height;
} else {
if ($ps_image_generation_method == 2 || (!$ps_image_generation_method && $width_diff > $height_diff)) {
$next_height = $dst_height;
$next_width = round(($src_width * $next_height) / $src_height);
$dst_width = (int)(!$ps_image_generation_method ? $dst_width : $next_width);
} else {
$next_width = $dst_width;
$next_height = round($src_height * $dst_width / $src_width);
$dst_height = (int)(!$ps_image_generation_method ? $dst_height : $next_height);
}
}
if (!ImageManager::checkImageMemoryLimit($src_file)) {
return !($error = self::ERROR_MEMORY_LIMIT);
}
$tgt_width = $dst_width;
$tgt_height = $dst_height;
$dest_image = imagecreatetruecolor($dst_width, $dst_height);
// If image is a PNG and the output is PNG, fill with transparency. Else fill with white background.
if ($file_type == 'png' && $type == IMAGETYPE_PNG) {
imagealphablending($dest_image, false);
imagesavealpha($dest_image, true);
$transparent = imagecolorallocatealpha($dest_image, 255, 255, 255, 127);
imagefilledrectangle($dest_image, 0, 0, $dst_width, $dst_height, $transparent);
} else {
$white = imagecolorallocate($dest_image, 255, 255, 255);
imagefilledrectangle($dest_image, 0, 0, $dst_width, $dst_height, $white);
}
$src_image = ImageManager::create($type, $src_file);
if ($rotate) {
$src_image = imagerotate($src_image, $rotate, 0);
}
if ($dst_width >= $src_width && $dst_height >= $src_height) {
imagecopyresized($dest_image, $src_image, (int)(($dst_width - $next_width) / 2), (int)(($dst_height - $next_height) / 2), 0, 0, $next_width, $next_height, $src_width, $src_height);
} else {
ImageManager::imagecopyresampled($dest_image, $src_image, (int)(($dst_width - $next_width) / 2), (int)(($dst_height - $next_height) / 2), 0, 0, $next_width, $next_height, $src_width, $src_height, $quality);
}
$write_file = ImageManager::write($file_type, $dest_image, $dst_file);
#imagedestroy($src_image);
return $write_file;
}
I also tried to change quality parameter to 100 or even changed image format to PNG in prestashop - no changes.
What else can I change to fix this quality issues? Any ideas?
I found a PHP script online which helps me to create a thumbnail of an uploaded image, there is only one problem: I don't know how to change the outcome size of the thumbnail. I found the tutorial at: http://www.w3schools.in/php/image-upload-and-generate-thumbnail-using-ajax-in-php/
Can anyone help me to change the outcome size of the thumbnail?
Here is my code so far:
<?php
function createDir($path){
if (!file_exists($path)) {
$old_mask = umask(0);
mkdir($path, 0777, TRUE);
umask($old_mask);
}
}
function createThumb($path1, $path2, $file_type, $new_w, $new_h, $squareSize = ''){
/* read the source image */
$source_image = FALSE;
if (preg_match("/jpg|JPG|jpeg|JPEG/", $file_type)) {
$source_image = imagecreatefromjpeg($path1);
}
elseif (preg_match("/png|PNG/", $file_type)) {
if (!$source_image = #imagecreatefrompng($path1)) {
$source_image = imagecreatefromjpeg($path1);
}
}
elseif (preg_match("/gif|GIF/", $file_type)) {
$source_image = imagecreatefromgif($path1);
}
if ($source_image == FALSE) {
$source_image = imagecreatefromjpeg($path1);
}
$orig_w = imageSX($source_image);
$orig_h = imageSY($source_image);
if ($orig_w < $new_w && $orig_h < $new_h) {
$desired_width = $orig_w;
$desired_height = $orig_h;
} else {
$scale = min($new_w / $orig_w, $new_h / $orig_h);
$desired_width = ceil($scale * $orig_w);
$desired_height = ceil($scale * $orig_h);
}
if ($squareSize != '') {
$desired_width = $desired_height = $squareSize;
}
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
// for PNG background white----------->
$kek = imagecolorallocate($virtual_image, 255, 255, 255);
imagefill($virtual_image, 0, 0, $kek);
if ($squareSize == '') {
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $orig_w, $orig_h);
} else {
$wm = $orig_w / $squareSize;
$hm = $orig_h / $squareSize;
$h_height = $squareSize / 2;
$w_height = $squareSize / 2;
if ($orig_w > $orig_h) {
$adjusted_width = $orig_w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $half_width - $w_height;
imagecopyresampled($virtual_image, $source_image, -$int_width, 0, 0, 0, $adjusted_width, $squareSize, $orig_w, $orig_h);
}
elseif (($orig_w <= $orig_h)) {
$adjusted_height = $orig_h / $wm;
$half_height = $adjusted_height / 2;
imagecopyresampled($virtual_image, $source_image, 0,0, 0, 0, $squareSize, $adjusted_height, $orig_w, $orig_h);
} else {
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $squareSize, $squareSize, $orig_w, $orig_h);
}
}
if (#imagejpeg($virtual_image, $path2, 90)) {
imagedestroy($virtual_image);
imagedestroy($source_image);
return TRUE;
} else {
return FALSE;
}
}
?>
the function gets called by the following lines of code:
<?php
include('./functions.php');
/*defined settings - start*/
ini_set("memory_limit", "99M");
ini_set('post_max_size', '20M');
ini_set('max_execution_time', 600);
define('IMAGE_SMALL_DIR', './uploades/small/');
define('IMAGE_SMALL_SIZE', 50);
define('IMAGE_MEDIUM_DIR', './uploades/medium/');
define('IMAGE_MEDIUM_SIZE', 250);
/*defined settings - end*/
if(isset($_FILES['image_upload_file'])){
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_upload_file']["error"] > 0) {
$output['error']= "Error in File";
}
elseif (!in_array($_FILES['image_upload_file']["type"], $allowedImageType)) {
$output['error']= "You can only upload JPG, PNG and GIF file";
}
elseif (round($_FILES['image_upload_file']["size"] / 1024) > 4096) {
$output['error']= "You can upload file size up to 4 MB";
} else {
/*create directory with 777 permission if not exist - start*/
createDir(IMAGE_SMALL_DIR);
createDir(IMAGE_MEDIUM_DIR);
/*create directory with 777 permission if not exist - end*/
$path[0] = $_FILES['image_upload_file']['tmp_name'];
$file = pathinfo($_FILES['image_upload_file']['name']);
$fileType = $file["extension"];
$desiredExt='jpg';
$fileNameNew = rand(333, 999) . time() . ".$desiredExt";
$path[1] = IMAGE_MEDIUM_DIR . $fileNameNew;
$path[2] = IMAGE_SMALL_DIR . $fileNameNew;
if (createThumb($path[0], $path[1], $fileType, IMAGE_MEDIUM_SIZE, IMAGE_MEDIUM_SIZE,IMAGE_MEDIUM_SIZE)) {
if (createThumb($path[1], $path[2],"$desiredExt", IMAGE_SMALL_SIZE, IMAGE_SMALL_SIZE,IMAGE_SMALL_SIZE)) {
$output['status']=TRUE;
$output['image_medium']= $path[1];
$output['image_small']= $path[2];
}
}
}
echo json_encode($output);
}
?>
I saw that you found the answer to your own problem. I wanted to add some additional insight.
The Right Way
Ideally you should be passing a param to the method as you can reset it if desired:
$imageSize = 100; // size
createThumb($path[0], $path[1], $fileType, $imageSize, $imageSize, $imageSize);
The Wrong Way
The script above is using constants. They are outlined with the define method. IE.
define('IMAGE_SMALL_SIZE', 50);
define('IMAGE_MEDIUM_SIZE', 250);
Change the number to your desired size. Ie
define('IMAGE_SMALL_SIZE', 150);
In this particular use case, the constants are still being passed into the function which defeats the need for a constant.
Final: I've decided to basically use this: http://shiftingpixel.com/2008/03/03/smart-image-resizer/
As it handles everything, Ive turned caching off and do this in the admin controllers:
$image = file_get_contents(SITE_ADMIN_IMAGE.'/SmartImage.php?width='.$this->thumb_width.'&height='.$this->thumb_height.'&image=/images/'.$this->image_directory.'/'.$formData['image_url'].'');
file_put_contents(ROOT_PATH.'/public/images/'.$this->image_directory.'/thumb/'.$formData['image_url'], $image);
EDIT: I found this works, however it creates very sharp edges, it doesn't look right.
imagecolortransparent($dstImage, $background);
imagealphablending($dstImage, false);
$colorTransparent = imagecolorallocatealpha($dstImage, 0, 0, 0, 127);
imagefill($dstImage, 0, 0, $colorTransparent);
imagesavealpha($dstImage, true);
imagepng($dstImage, $toWhere);
Ideas?
Hello,
I have two issues with my class, basically the quality of the jpeg images is quite poor, but I'm not sure if thats down to my ratio resizing. Ideally I'd like this class to be strict with image sizes and crop into them, but I cant get my head around it.
My main issue is that pngs always have a black bg, does anyone have experience with this happening?
<?php
class OpenSource_ImageResize {
function __construct($theFile, $toWhere, $mime, $extension, $newWidth, $newHeight) {
if ($mime == NULL) {
$mime = getimagesize($theFile);
$mime = $mime['mime'];
}
if ($mime == 'image/jpeg') {
$size = getimagesize($theFile);
if ($size[0] > $newWidth || $size[1] > $newHeight) {
$sourceImage = imagecreatefromjpeg($theFile);
} else {
return copy($theFile, $toWhere);
throw new exception('Could not create jpeg');
return false;
}
} else if ($mime == 'image/png') {
$size = getimagesize($theFile);
if ($size[0] > $newWidth || $size[1] > $newHeight) {
$sourceImage = imagecreatefrompng($theFile);
} else {
return copy($theFile, $toWhere);
//throw new exception('Could not create png');
return false;
}
} else if ($mime == 'image/gif') {
$size = getimagesize($theFile);
if ($size[0] > $newWidth || $size[1] > $newHeight) {
$sourceImage = imagecreatefromgif ($theFile);
} else {
return copy($theFile, $toWhere);
//throw new exception('Could not create gif');
return false;
}
} else {
throw new exception('Not a valid mime type');
return false;
}
$oldX = imageSX($sourceImage);
$oldY = imageSY($sourceImage);
if ($newWidth == NULL) {
$thumbHeight = $newHeight;
$thumbWidth = round($newHeight/($oldY/$oldX));
} else
if ($oldX > $oldY) {
$thumbWidth = $newWidth;
$thumbHeight = $oldY * ($newHeight/$oldX);
}
if ($oldX < $oldY) {
$thumbWidth = round($newHeight/($oldY/$oldX));
$thumbHeight = $newHeight;
}
if ($oldX == $oldY) {
$thumbWidth = $newWidth;
$thumbHeight = $newHeight;
}
if (!gd_info()) {
$dstImage = ImageCreate($thumbWidth, $thumbHeight);
imagecopyresized($dstImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $oldX, $oldY);
} else {
$dstImage = ImageCreateTrueColor($thumbWidth, $thumbHeight);
imagecopyresampled($dstImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $oldX, $oldY);
}
if ($mime == 'image/png') {
$xparent = imagecolorresolvealpha($dstImage, 255,2,240, 0) ;
imagecolortransparent($dstImage,$xparent);
imagealphablending($dstImage,true);
imagepng($dstImage, $toWhere);
} else if ($mime == 'image/jpeg') {
imagejpeg($dstImage, $toWhere);
} else if ($mime == 'image/gif') {
imagegif ($dstImage, $toWhere);
}
imagedestroy($dstImage);
imagedestroy($sourceImage);
return true;
}
}
Regarding JPEG image quality you need to make use of the third argument in imagejpeg():
imagejpeg($dstImage, $toWhere, 90); // any value above 85 should be fine
Regarding PNG transparency, you're doing it wrong. Your script is horrible and has fundamental problems, I'm gonna leave you with a revised one that fixes both of your problems. It can still be further optimized but I choose to leave some of your original less important mistakes so you don't feel lost:
class OpenSource_ImageResize
{
// $extension is not used?
function __construct($theFile, $toWhere, $mime, $extension, $newWidth, $newHeight)
{
$sourceImage = ImageCreateFromString(file_get_contents($theFile));
if (is_resource($sourceImage))
{
$info = getimagesize($theFile);
if (is_null($mime))
{
$mime = $info['mime'];
}
if ($info[0] <= $newWidth && $info[1] <= $newHeight)
{
imagedestroy($sourceImage);
return copy($theFile, $toWhere);
}
if (is_null($newWidth))
{
$thumbHeight = $newHeight;
$thumbWidth = round($newHeight/($info[1]/$info[0]));
}
else if ($info[0] > $info[1])
{
$thumbWidth = $newWidth;
$thumbHeight = $info[1] * ($newHeight/$info[0]);
}
if ($info[0] < $info[1])
{
$thumbWidth = round($newHeight/($info[1]/$info[0]));
$thumbHeight = $newHeight;
}
if ($info[0] == $info[1])
{
$thumbWidth = $newWidth;
$thumbHeight = $newHeight;
}
$dstImage = ImageCreateTrueColor($thumbWidth, $thumbHeight);
/* fix PNG transparency issues */
ImageFill($dstImage, 0, 0, IMG_COLOR_TRANSPARENT);
ImageSaveAlpha($dstImage, true);
ImageAlphaBlending($dstImage, true);
imagecopyresampled($dstImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $info[0], $info[1]);
switch ($mime)
{
case 'image/png':
imagepng($dstImage, $toWhere, 9); // compress it (level 1 to 9)
break;
case 'image/jpeg':
imagejpeg($dstImage, $toWhere, 90); // quality = 90 (1 to 100, default is "about" 75)
break;
case 'image/gif':
imagegif($dstImage, $toWhere);
break;
}
imagedestroy($dstImage);
imagedestroy($sourceImage);
return true;
}
}
}
I'm sorry for not explicitly pointing out your mistakes but they are so many and it's 3 AM here, need to get some sleep - study it and read the manual, if you have any doubts let me know.
Musty define in your class png background color.You can also change the background color of jpg and other files after defining the background color.
this link will take you to a simple function that will either crop-to-fit, or letter box the image during resize based on the function's arguments. it also has a pretty thorough explaination as to what the function is doing.
http://www.spotlesswebdesign.com/blog.php?id=1
Edit: fixed link.