I'm attempting to allow transparency when compressing a file upload.
I created a function in which it will change the image to a jpeg (no matter what is uploaded), however, my client wants the images to have transparency. For ease, what I will do is if the image is a PNG, I will save it out as a PNG with transparency enabled, otherwise, I will just save it as a "flat" jPEG.
Here is the function I created.
function resizeImage($image, $resizeHeight = null, $resizeWidth = null, $quality = 80)
{
$img = getimagesize($image);
$ext = explode(".",$image);
list($width, $height, $type, $attr) = $img;
if($resizeHeight == null)
{
//Getting the new height by dividing the image width by the height and multiplying by the new width.
$resizeHeight = ($height/$width)*$resizeWidth;
}
if($resizeWidth == null)
{
//Getting the new width by dividing the image height by the width and multiplying by the new height.
$resizeWidth = ($width/$height)*$resizeHeight;
}
$name = uniqid().time().".".$ext[count($ext)-1];
if($img['mime'] == "image/jpeg")
{
$image = imagecreatefromjpeg($image);
}
else if($img['mime'] == "image/png")
{
$image = imagecreatefrompng($image);
}
$destImg = imagecreatetruecolor($resizeWidth, $resizeHeight);
if(imagecopyresampled($destImg, $image, 0, 0, 0, 0, $resizeWidth, $resizeHeight, $width, $height))
{
if(imagejpeg($destImg, DIRUPLOADFOLDER.$name, $quality))
{
return $name;
}
}
}
Needless to say, this function only saves out as a JPEG. I tried replacing imagejpeg with imagepng but that didn't work (like it didn't at all create an image). What do I need to do in order to make sure that the saved out PNG will also save out with the original's transparency?
Related
I'm using the following PHP function to resize big images to fit 500 px width:
<?php
function resizeImage($name) {
header('Content-type: image/jpeg');
$filename = "file.jpg";
$new_width = 500;
list($width, $height) = getimagesize($filename);
$new_height = (($height*$new_width)/$width);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, "file.jpg", 100);
}
?>
For some reason the colors on the resized image aren't exactly the same as before. They aren't as clear and strong as before. As you can see [picture removed] there's more red color and brilliance in the left (original) photo.
Why that? Is there something wrong with my script? Or is it a normal resizing effect?
This is the working code I have now:
<?php
// Call the function with: resizeImage("INSERT_YOUR_FILE_NAME_INCLUDING_SUFFIX_HERE");
function resizeImage($file_name) {
// File is located at: files/original/
$filename = "files/original/".$file_name;
// The width you want the converted image has
$new_width = 500;
// Calculate right height
list($width, $height) = getimagesize($filename);
$new_height = (($height*$new_width)/$width);
// Get image
$small = new Imagick($filename);
// Resize image, but only if original image is wider what the wanted 500 px
if($width > $new_width) {$small->resizeImage($new_width, $new_height, Imagick::FILTER_LANCZOS, 1);}
// Some code to correct the color profile
$version = $small->getVersion();
$profile = "sRGB_IEC61966-2-1_no_black_scaling.icc";
if((is_array($version) === true) && (array_key_exists("versionString", $version) === true)) {$version = preg_replace("~ImageMagick ([^-]*).*~", "$1", $version["versionString"]);if(is_file(sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version)) === true) {$profile = sprintf("/usr/share/ImageMagick-%s/config/sRGB.icm", $version);}}if(($srgb = file_get_contents($profile)) !== false){$small->profileImage("icc", $srgb);$small->setImageColorSpace(Imagick::COLORSPACE_SRGB);}
// Safe the image to: files/small/
$small->writeImage("files/small/".$file_name);
// Clear all resources associated to the Imagick object
$small->clear();
}
?>
Don't forget to either download the icc file from http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc and save it in the same directory as your resize file or change $profile = "sRGB_IEC61966-2-1_no_black_scaling.icc"; to $profile = "http://www.color.org/sRGB_IEC61966-2-1_no_black_scaling.icc";!
I'm creating thumbnails using php, and it is working fine for GIF and JPEG, but not for PNG. When I run this script, with a PNG, a thumbnail doesn't save. Can you show me what I am doing wrong? Thanks in advance!
public function make_thumbs($img_src)
{
//Desired thumbnail width
$width = 100;
//Thumbnail name
$thumb = 'th_' . $img_src;
//Ensure the image exists
if(file_exists($img_src)){
if (exif_imagetype($img_src) == IMAGETYPE_GIF)
{
//Create image stream
$image = imagecreatefromgif($img_src);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_JPEG)
{
//Create image stream
$image = imagecreatefromjpeg($img_src);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_PNG)
{
//Create image stream
$image = imagecreatefrompng($img_src);
}
//Gather and store the width and height
list($image_width, $image_height) = getimagesize($img_src);
//Calculate new height while maintaining aspect ratio
$height = (($width / $image_width) * $image_height);
//Resample/resize the image
$tmp_img = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp_img, $image, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
//Attempt to save the new thumbnail
if(is_writeable(dirname($thumb)))
{
if (exif_imagetype($img_src) == IMAGETYPE_GIF)
{
imagegif($tmp_img, $thumb, 100);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_JPEG)
{
imagejpeg($tmp_img, $thumb, 100);
}
elseif(exif_imagetype($img_src) == IMAGETYPE_PNG)
{
imagepng($tmp_img, $thumb, 100);
}
}
//clear memory
imagedestroy($tmp_img);
imagedestroy($image);
}
}
I have an image whose size is "300X367" .
I have an image function which crop thumbnail by using this type
but this function crop thumbnail of "41X50". I think it crop thumbnail by scale of original image.
But I want accurate thumbnail size of passing parameter. I can't put code here of image.php as the size is too big.
If anyone have solution for passing size parameter in image tag & crop thumbnail. please tell me.
Try this example code
<?php
function getFileExtenction($image)
{
$imageAry = explode(".", $image);
return $imageAry[1];
}
$image = 'images/imageName.png'; //Your image location
$imageType = getFileExtenction($image); //check the image file type
if ($imageType == "png")
$src = imagecreatefrompng($image);
else if ($imageType == "jpg")
$src = imagecreatefromjpeg($image);
else if ($imageType == "gif")
$src = imagecreatefromgif($image);
else
{
}
list($width, $height) = getimagesize($image); //To get the image width and height
$newwidth = 41; //Give your thumbanail image width
$newheight = 50; //Give your thubnail image height
$tmp = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename = "NewImagename." . $imageType;
/*========== if you want to store this file in a folder Ex: "thumbs" ==========
$filename = "thumbs/NewImagename." . $imageType;
*/
imagejpeg($tmp, $filename, 100);
imagedestroy($src);
imagedestroy($tmp);
?>
I need to help a friend to make his own artistic gallery.
I already have all done, but I need a tool/plugin/script to make him independent from me in uploading his own images. My gallery needs two images: a cropped one of a certain proportion (so i need him to crop by himself in an uploading page) and a thumb one (I want this be done automatically).
Do you know an easy way to do this? What would you do?
Thanks.
Personally i use this in all of my projects - http://www.verot.net/php_class_upload.htm
Works perfectly with upload files and with files that's already on the system.
Can do many things convert, resize and work on uploaded images in many ways, apply effects, add labels, watermarks and reflections and other image editing features.
Easy to work with.
If you're not going to be having heavy traffic to start - look at http://phpthumb.sourceforge.net/ which can create your resized images on the fly.
You need only GD library, function imagecopyresampled will suit you. PHP manual has really good example code for thumbnail creation http://php.net/manual/en/function.imagecopyresampled.php
You will need just to create exceptions for different file formats
function create_jpeg_thumbnail($thumbImageName,$imgSrc,$thumbDirectory,$thumbnail_width,$thumbnail_height) { //$imgSrc is a FILE - Returns an image resource.
$thumbDirectory = trim($thumbDirectory);
$imageSourceExploded = explode('/', $imgSrc);
$imageName = $imageSourceExploded[count($imageSourceExploded)-1];
$imageDirectory = str_replace($imageName, '', $imgSrc);
$filetype = explode('.',$imageName);
$filetype = strtolower($filetype[count($filetype)-1]);
//getting the image dimensions
list($width_orig, $height_orig) = getimagesize($imgSrc);
//$myImage = imagecreatefromjpeg($imgSrc);
if ($filetype == 'jpg') {
$myImage = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
$myImage = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'png') {
$myImage = imagecreatefrompng("$imageDirectory/$imageName");
} else
if ($filetype == 'gif') {
$myImage = imagecreatefromgif("$imageDirectory/$imageName");
}
$ratio_orig = $width_orig/$height_orig;
if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
} else {
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width/2; //horizontal middle
$y_mid = $new_height/2; //vertical middle
$process = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumb, $process, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
//$thumbImageName = 'thumb_'.get_random_no().'.jpeg';
$destination = $thumbDirectory=='' ? $thumbImageName : $thumbDirectory."/".$thumbImageName;
imagejpeg($thumb, $destination, 100);
return $thumbImageName;
}
I'm currently coding an uploader script based on Uploadify. Right now I resize the given image and watermark one of the sizes. It all works well, but I need the script to resize the height and then crop the width so that the aspect ratio does not get messed up.
This is my code so far:
if ($fileExtension == "jpg" ||
$fileExtension == "jpeg" ||
$fileExtension == "png" ||
$fileExtension == "gif"){
// GD variables:
list($width, $height, $type) = GetImageSize($uploadedFile['tmp_name']);
// Image sizes:
$bigImage = array(800, 453);
$mediumImage = array(410, 231);
$listImage = array(120, 68);
$thumbnail = array(90, 51);
$sourceAspect = $width / $height;
$bigAspect = $bigImage[0] / $bigImage[1];
$mediumAspect = $mediumImage[0] / $mediumImage[1];
$listAspect = $listImage[0] / $listImage[1];
$thumbnailAspect = $thumbnail[0] / $thumbnail[1];
// Image is PNG:
if ($type == IMAGETYPE_PNG){
$image = imagecreatefrompng($uploadedFile['tmp_name']);
$valid = true;
}
// Image is JPEG:
else if ($type == IMAGETYPE_JPEG){
$image = imagecreatefromjpeg($uploadedFile['tmp_name']);
$valid = true;
}
// Image is GIF:
else if ($type == IMAGETYPE_GIF){
$image = imagecreatefromgif($uploadedFile['tmp_name']);
$valid = true;
}
// Format not allowed:
else {
$valid = false;
}
// Start creating images:
if ($valid){
// Get size:
$imageSize = getimagesize($uploadedFile['tmp_name']);
// Generate canvas:
$bCanvas = imagecreatetruecolor($bigImage[0], $bigImage[1]);
$mCanvas = imagecreatetruecolor($mediumImage[0], $mediumImage[1]);
$lCanvas = imagecreatetruecolor($listImage[0], $listImage[1]);
$tCanvas = imagecreatetruecolor($thumbnail[0], $thumbnail[1]);
// Copy content:
imagecopyresampled($bCanvas, $image, 0, 0, 0, 0, ($bigImage[0] * $sourceAspect), ($bigImage[1] / $sourceAspect), $imageSize[0], $imageSize[1]);
imagecopyresampled($mCanvas, $image, 0, 0, 0, 0, $mediumImage[0], $mediumImage[1], $imageSize[0], $imageSize[1]);
imagecopyresampled($lCanvas, $image, 0, 0, 0, 0, $listImage[0], $listImage[1], $imageSize[0], $imageSize[1]);
imagecopyresampled($tCanvas, $image, 0, 0, 0, 0, $thumbnail[0], $thumbnail[1], $imageSize[0], $imageSize[1]);
// Save images:
$saveB = imagejpeg($bCanvas, $targetFile.'_big.jpg', 90);
$saveM = imagejpeg($mCanvas, $targetFile.'_medium.jpg', 90);
$saveT = imagejpeg($lCanvas, $targetFile.'_list.jpg', 90);
$saveT = imagejpeg($tCanvas, $targetFile.'_thumb.jpg', 90);
// Destroy images:
imagedestroy($image);
imagedestroy($bCanvas);
imagedestroy($mCanvas);
imagedestroy($lCanvas);
imagedestroy($tCanvas);
// Watermark images:
$mark = imagecreatefrompng("logo.png");
list($mwidth, $mheight) = getimagesize("logo.png");
$img = imagecreatefromjpeg($targetFile.'_big.jpg');
list($bwidth, $bheight) = getimagesize($targetFile.'_big.jpg');
imagecopy($img, $mark, $bwidth-$mwidth-25, $bheight-$mheight-25, 0, 0, $mwidth, $mheight);
imagejpeg($img, $targetFile.'_big.jpg', 100);
imagedestroy($img);
} else {
echo "0";
}
} else {
move_uploaded_file($tempFile,$targetFile.'.'.$fileExtension);
}
I would be really happy if someone could help me solve this. I've been trying several methods but none of them seemed to work properly. As you can see in the top I have already defined the canvas sizes that I want to use in the variables "bigImage", "mediumImage", "listImage" and "thumbnail".
Thanks in advance! //
Jonathan
There is more than one way to resize an image. I'll spell them out for you:
Stretch to fit -- the image is resized to the desired size ignoring aspect ratio
Scale to fit -- the image is resized so that one dimension (width or height) has the desired size while the other is same or shorter while maintaining aspect ratio (one extra step may be required to fill the shorter side with solid color)
Crop to fit -- the image is resized so that one dimension (width or height) has the desired size while the other is same or longer while maintaining aspect ratio (one extra step is required to trim the outside region)
PS: both articles were written by me.