I have been trying to get a PNG to upload with a clean, 24 bit alpha transparency. After doing a lot of research, I have managed to get it sort of working, however the transparency seems to be low quality 8 bit as you can see here in this screenshot:
http://cozomo.com/apple.png
Any help to achieve a clean PNG upload and resize with 24 bit smooth transparency would be much appreciated. My current code is below.
if($extension=="png")
{
$uploadedfile = $_FILES['photo']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
$dest_x = 1400;
$dest_y = 1200;
if ($width > $dest_x or $height > $dest_y) {
if ($width >= $height) {
$fullSize_x = $dest_x;
$fullSize_y = $height*($fullSize_x/$width);
} else {
$fullSize_x = $width*($fullSize_y/$height);
$fullSize_y = $dest_y;
}
}
$fullSize=imagecreatetruecolor($fullSize_x,$fullSize_y);
//TEST
$black = imagecolorallocate($fullSize, 0, 0, 0);
imagecolortransparent($fullSize, $black);
//TEST END
// OUTPUT NEW IMAGES
imagecopyresampled($fullSize,$src,0,0,0,0,$fullSize_x,$fullSize_y,$width,$height);
imagepng($fullSize, "/user/photos/".$filename);
imagedestroy($fullSize);
[1]: http://i.stack.imgur.com/w8VBI.png
To save the full alpha channel you'll have to use imagesavealpha, put this before you save the png
imagealphablending($fullSize, false);
imagesavealpha($fullSize, true);
Here is the revised code thanks to Musa for anyone having the same issue
function processPNG($pngImage) {
$black = imagecolorallocate($pngImage, 0, 0, 0);
imagecolortransparent($pngImage, $black);
imagealphablending($pngImage, false);
imagesavealpha($pngImage, true);
}
if($extension=="png")
{
$uploadedfile = $_FILES['photo']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
$dest_x = 1400;
$dest_y = 1200;
if ($width > $dest_x or $height > $dest_y) {
if ($width >= $height) {
$fullSize_x = $dest_x;
$fullSize_y = $height*($fullSize_x/$width);
} else {
$fullSize_x = $width*($fullSize_y/$height);
$fullSize_y = $dest_y;
}
}
$fullSize=imagecreatetruecolor($fullSize_x,$fullSize_y);
if ($extension == "png") processPNG($fullSize);
// OUTPUT NEW IMAGES
imagecopyresampled($fullSize,$src,0,0,0,0,$fullSize_x,$fullSize_y,$width,$height);
imagepng($fullSize, "/user/photos/".$filename);
imagedestroy($fullSize);
Related
I am attempting to create and save a squared version (thumb) of an uploaded image file with php. My current script crops it as it should, but the image is completely black. Here is my code:
if ($_FILES['profile_pic']['type'] == "image/png") {
$is_image = true;
$newImage = imagecreatefrompng($img);
} else if ($_FILES['profile_pic']['type'] == "image/jpeg") {
$is_image = true;
$newImage = imagecreatefromjpeg($img);
} else if ($_FILES['profile_pic']['type'] == "image/gif") {
$is_image = true;
$newImage = imagecreatefromgif($img);
} else {
$is_image = false;
}
$img = $_FILES["profile_pic"]['tmp_name'];
$min_width = 100;
$min_height = 100;
$width = 0;
$height = 0;
if ($is_image) {
list($width, $height) = getimagesize($img);
}
if ($is_image && $height >= $min_height && $width >= $min_width) {
$img = $_FILES["profile_pic"]['tmp_name'];
$imgPath = "../img/profile_pics/{$member_id}.png";
// Resize
$aspect_ratio = $width / $min_width;
$new_height = $height * $aspect_ratio;
$canvas1 = imagecreatetruecolor($min_width, $new_height);
imagecopyresampled($canvas1, $newImage, 0, 0, 0, 0, $min_width, $new_height, $width, $new_height);
// Crop
$canvas2 = imagecreatetruecolor($min_width, $min_height);
imagecopyresampled($canvas2, $newImage, 0, 0, 0, 0, $min_width, $min_height, $min_width, $min_height);
imagejpeg($canvas2, $imgPath, 80);
imagedestroy($canvas1);
}
I realise that there this question has been asked before, but for some reason I can't seem to make my own script work.
You're initializing $img after you try to create it via imagecreatefrompng($img) or similar. Might be the reason why it fails.
I'm also not sure you want to save all your images into a *.png file, regardless of their source type: you might want to implement something more flexible instead.
I am working in PHP and trying to use iMagick library to do an image conversion from SVG to JPG using shell_exec command. All seems to work, but the output JPG comes out very distorted. I almost get a feeling that the image is first converted and then resized.
I tried using "resize" and "scale" with same results.
Here is the command:
"-resize 800x800 -quality 95 image.svg image.jpg"
Any insights? Thanks in advance.
For anyone looking for a solution to this. Someone was able to come up with the following hack (with some of my edits):
createThumbnail("input.svg", "output.jpg", 500, 500, $cdn_container);
function createThumbnail($filename, $thname, $width=100, $height=100, $cdn=null)
{
try {
$extension = substr($filename, (strrpos($filename, '.')) + 1 - strlen($filename));
$fallback_save_path = "images/designs";
if ($extension == "svg") {
$im = new Imagick();
$svgdata = file_get_contents($filename);
$svgdata = svgScaleHack($svgdata, $width, $height);
//$im->setBackgroundColor(new ImagickPixel('transparent'));
$im->readImageBlob($svgdata);
$im->setImageFormat("jpg");
$im->resizeImage($width, $height, imagick::FILTER_LANCZOS, 1);
$raw_data = $im->getImageBlob();
(is_null($cdn)) ? file_put_contents($fallback_save_path . '/' . $thname, $im->getImageBlob()) : '';
} else if ($extension == "jpg") {
$im = new Imagick($filename);
$im->stripImage();
// Save as progressive JPEG
$im->setInterlaceScheme(Imagick::INTERLACE_PLANE);
$raw_data = $im->resizeImage($width, $height, imagick::FILTER_LANCZOS, 1);
// Set quality
// $im->setImageCompressionQuality(85);
(is_null($cdn)) ? $im->writeImage($fallback_save_path . '/' . $thname) : '';
}
if (!is_null($cdn)) {
$imageObject = $cdn->DataObject();
$imageObject->SetData( $raw_data );
$imageObject->name = $thname;
$imageObject->content_type = 'image/jpg';
$imageObject->Create();
}
$im->clear();
$im->destroy();
return true;
}
catch(Exception $e) {
return false;
}
}
function svgScaleHack($svg, $minWidth, $minHeight)
{
$reW = '/(.*<svg[^>]* width=")([\d.]+px)(.*)/si';
$reH = '/(.*<svg[^>]* height=")([\d.]+px)(.*)/si';
preg_match($reW, $svg, $mw);
preg_match($reH, $svg, $mh);
$width = floatval($mw[2]);
$height = floatval($mh[2]);
if (!$width || !$height) return false;
// scale to make width and height big enough
$scale = 1;
if ($width < $minWidth)
$scale = $minWidth/$width;
if ($height < $minHeight)
$scale = max($scale, ($minHeight/$height));
$width *= $scale*2;
$height *= $scale*2;
$svg = preg_replace($reW, "\${1}{$width}px\${3}", $svg);
$svg = preg_replace($reH, "\${1}{$height}px\${3}", $svg);
return $svg;
}
I'm using a php script to upload and resize an image, pretty simple:
if($_SERVER["REQUEST_METHOD"] == "POST") {
$image = $_FILES["image_upload"];
$uploadedfile = $image['tmp_name'];
if ($image) {
$filename = stripslashes($_FILES['image_upload']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$error_txt = 'Immagine incoretta';
$errors=1;
} else {
$size=filesize($uploadedfile);
if ($size > MAX_SIZE*1024) {
$error_txt = "Immagine troppo grande";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" ) {
$uploadedfile = $uploadedfile;
$src = imagecreatefromjpeg($uploadedfile);
} else if($extension=="png") {
$uploadedfile = $uploadedfile;
$src = imagecreatefrompng($uploadedfile);
} else {
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=500;
$newheight=375;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "images/". generateRandomString(5) . $image['name'];
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
}
}
I want to got a bit further, right now im just resizing the image no matter the proportions, the think is, i want to resize it to a fixed with and height without losing the original proportion, and this of course is achieved through the cropping+resize of the original image.
I have no idea how to do this using my actual imagecreatetruecolor and imagecopyresampled functions, and looking to the php manual seems is not very easy.
There is a very good library im trying to integrate to my code, the use its as simple as mysite.com/lib/timthumb.php?src=castle1.jpg&h=180&w=120 but i dont know how to integrate that with my actual code.
So, what do you suggest?
Please forgive me if there are any typos or anything in the following code. I haven't tested it. What I've done here is calculate whether the height or the width is the proportion that's too long. Then adjust the source dimension to match the final image dimension. Also, adjust the center of the side that we shrunk so the cropped image is centered.
$newwidth = 500;
$newheight = 375;
$tmp = imagecreatetruecolor($newwidth, $newheight);
$widthProportion = $width / $newwidth;
$heightProportion = $height / $newheight;
if ($widthProportion > $heightProportion) {
// width proportion is greater than height proportion
// figure out adjustment we need to make to width
$widthAdjustment = ($width * ($widthProportion - $heightProportion));
// Shrink width to proper proportion
$width = $width - $widthAdjustment;
$x = 0; // No adjusting height position
$y = $y + ($widthAdjustment / 2); // Center the adjustment
} else {
// height proportion is greater than width proportion
// figure out adjustment we need to make to width
$heightAdjustment = ($height * ($heightProportion - $widthProportion));
// Shrink height to proper proportion
$height = $height - $heightAdjustment;
$x = $x + ($heightAdjustment / 2); // Center the ajustment
$y = 0; // No adjusting width position
}
imagecopyresampled($tmp, $src, 0, 0, $x, $y, $newwidth, $newheight, $width, $height);
So basically with the $width and $height variables you are specifying how much of the picture you want (cropping). and with the $x, $y we're saying where we want to crop the picture. The rest is just the standard resizing to fit the full new image.
I hope that helps!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can anybody suggest the best image resize script in php?
I'm still a newbie regarding image handling or file handling for that matter in PHP.
Would appreciate any input regarding the following
I post an image file using a simple html form and upload it via php.
When i try and alter my code to accomodate larger files (i.e. resize) I get an error.
Have been searching online but cant find anything really simple.
$size = getimagesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size == FALSE)
{
$errors=1;
}else if($size[0] > 300){ //if width greater than 300px
$aspectRatio = 300 / $size[0];
$newWidth = round($aspectRatio * $size[0]);
$newHeight = round($aspectRatio * $size[1]);
$imgHolder = imagecreatetruecolor($newWidth,$newHeight);
}
$newname= ROOTPATH.LOCALDIR."/images/".$image_name; //image_name is generated
$copy = imagecopyresized($imgHolder, $_FILES['image']['tmp_name'], 0, 0, 0, 0, $newWidth, $newHeight, $size[0], $size[1]);
move_uploaded_file($copy, $newname); //where I want to move the file to the location of $newname
The error I get is:
imagecopyresized(): supplied argument
is not a valid Image resource in
Thanks in advance
Thanks for all your input, i've changed it to this
$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));
$copy = imagecopyresized($imgHolder, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $size[0], $size[1]);
if(!move_uploaded_file($copy, $newname)){
$errors=1;
}
Not getting a PHP log error but its not saving :(
Any ideas?
Thanks again
Result
Following works.
$oldImage = imagecreatefromjpeg($img);
$imageHolder = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($imageHolder, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($imageHolder, $newname, 100);
Thanks for everyones help
imagecopyresized takes an image resource as its second parameter, not a file name. You'll need to load the file first. If you know the file type, you can use imagecreatefromFILETYPE to load it. For example, if it's a JPEG, use imagecreatefromjpeg and pass that the file name - this will return an image resource.
If you don't know the file type, all is not lost. You can read the file in as a string and use imagecreatefromstring (which detects file types automatically) to load it as follows:
$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));
$_FILES['image']['tmp_name'] is path not image resource. You have to use one of imagecreatefrom*() functions to create resource.
Here is my implementation of saving a thumbnail picture:
Resize and save function:
function SaveThumbnail($imagePath, $saveAs, $max_x, $max_y)
{
ini_set("memory_limit","32M");
$im = imagecreatefromjpeg ($imagePath);
$x = imagesx($im);
$y = imagesy($im);
if (($max_x/$max_y) < ($x/$y))
{
$save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
}
else
{
$save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
}
imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);
imagejpeg($save, $saveAs);
imagedestroy($im);
imagedestroy($save);
}
Usage:
$thumb_dir = "/path/to/thumbnaildir/"
$thumb_name = "thumb.jpg"
$muf = move_uploaded_file($_FILES['imgfile']['tmp_name'], "/tmp/test.jpg")
if($muf)
{
SaveThumbnail("/tmp/test.jpg", $thumb_dir . $thumb_name, 128, 128);
}
I use ImageMagick for stuff like that. Look how much simpler it is!
An example from one of my scripts:
$target= //destination path
move_uploaded_file($_FILES['item']['tmp_name'],$target);
$image = new imagick($target);
$image->setImageColorspace(imagick::COLORSPACE_RGB);
$image->scaleImage(350,0);
$image->writeImage($target);
You could then use getImageGeometry() to obtain the width and height.
For example:
$size=$image->getImageGeometry();
if($size['width'] > 300){ //if width greater than
$image->scaleImage(300,0);
}
Also, using scaleImage(300,0) means that ImageMagick automatically calculates the height based on the aspect ratio.
I was working on sth similar. I tried Ghostscript and ImageMagic. They are good tools but takes a but of time to set up. I ended up using 'sips' on a Snow Leopard server. Not sure if it's built in to Linux server but it's the faster solution I have found if you need sth done quick.
function resizeImage($file){
define ('MAX_WIDTH', 1500);//max image width
define ('MAX_HEIGHT', 1500);//max image height
define ('MAX_FILE_SIZE', 10485760);
//iamge save path
$path = 'storeResize/';
//size of the resize image
$new_width = 128;
$new_height = 128;
//name of the new image
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
$image_type = $file['type'];
$image_size = $file['size'];
$image_error = $file['error'];
$image_file = $file['tmp_name'];
$image_name = $file['name'];
$image_info = getimagesize($image_file);
//check image type
if ($image_info['mime'] == 'image/jpeg' or $image_info['mime'] == 'image/jpg'){
}
else if ($image_info['mime'] == 'image/png'){
}
else if ($image_info['mime'] == 'image/gif'){
}
else{
//set error invalid file type
}
if ($image_error){
//set error image upload error
}
if ( $image_size > MAX_FILE_SIZE ){
//set error image size invalid
}
switch ($image_info['mime']) {
case 'image/jpg': //This isn't a valid mime type so we should probably remove it
case 'image/jpeg':
$image = imagecreatefromjpeg ($image_file);
break;
case 'image/png':
$image = imagecreatefrompng ($image_file);
break;
case 'image/gif':
$image = imagecreatefromgif ($image_file);
break;
}
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
$new_width = min ($new_width, MAX_WIDTH);
$new_height = min ($new_height, MAX_HEIGHT);
//get original image h/w
$width = imagesx ($image);
$height = imagesy ($image);
//$align = 'b';
$zoom_crop = 1;
$origin_x = 0;
$origin_y = 0;
//TODO setting Memory
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
$new_width = floor ($width * ($new_height / $height));
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
} else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
if (strlen ($canvas_color) < 6) {
$canvas_color = 'ffffff';
}
$canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
$canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
$canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
// Create a new transparent color for image
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$origin_x = $new_width / 2;
$new_width = $width * ($new_height / $height);
$origin_x = round ($origin_x - ($new_width / 2));
} else {
$origin_y = $new_height / 2;
$new_height = $final_height;
$origin_y = round ($origin_y - ($new_height / 2));
}
}
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop > 0) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round ($width / $cmp_x * $cmp_y);
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} else if ($cmp_y > $cmp_x) {
$src_h = round ($height / $cmp_y * $cmp_x);
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
if ($align) {
if (strpos ($align, 't') !== false) {
$src_y = 0;
}
if (strpos ($align, 'b') !== false) {
$src_y = $height - $src_h;
}
if (strpos ($align, 'l') !== false) {
$src_x = 0;
}
if (strpos ($align, 'r') !== false) {
$src_x = $width - $src_w;
}
}
// positional cropping!
imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
//Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
if ( (IMAGETYPE_PNG == $image_info[2] || IMAGETYPE_GIF == $image_info[2]) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
}
$quality = 100;
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
if (preg_match('/^image\/(?:jpg|jpeg)$/i', $image_info['mime'])){
imagejpeg($canvas, $path.$nameOfFile, $quality);
} else if (preg_match('/^image\/png$/i', $image_info['mime'])){
imagepng($canvas, $path.$nameOfFile, floor($quality * 0.09));
} else if (preg_match('/^image\/gif$/i', $image_info['mime'])){
imagegif($canvas, $path.$nameOfFile);
}
}
I am doing PNG image cropping using this function. Everything is working fine, but whenever I upload the .png, the image background color is changed to black. Here is the code.
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments3";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
} `
even i tried like this also
/************************************Resizing the image 80*60****************/
$path3="partners_logs";
$filetype3=$_FILES["pimage"]["type"];
$bgim_file_name = $path3."/".$Attachments2;
$bgimage_attribs = getimagesize($bgim_file_name);
if($filetype3=='image/gif')
{
$bgim_old = imagecreatefromgif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
$bgim_old = imagecreatefromjpeg($bgim_file_name);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
$bgim_old = imagecreatefrompng($bgim_file_name);
imageAlphaBlending($bgim_old, true);
imageSaveAlpha($bgim_old, true);
}
$bgth_max_width =265; //for Album image
$bgth_max_height =150;
$bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
$bgth_width =265;//$image_attribs[0] * $ratio;
$bgth_height =150;//$image_attribs[1] * $ratio;
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
$bgth_file_name = "partners_logs/250x150/$Attachments2";
imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
if($filetype3=='image/gif')
{
imagegif($bgim_new,$bgth_file_name,100);
//$bgim_old = imagegif($bgim_file_name);
}
else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))
{
imagejpeg($bgim_new,$bgth_file_name,100);
}
else if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
{
imagepng($bgim_new,$bgth_file_name,9);
//set the background color to your choice, paramters are int values of red,green and blue
imagecolorallocate($bgim_new,0xFF,0xFF,0xFF);
}
/************End Resize of 80*60*******************/
maybe this helps
Don't forget about
imagealphablending() and
imagesavealpha() if you're working
with [semi]transparent png.
<?php
$file = 'semitransparent.png'; // path to png image
$img = imagecreatefrompng($file); // open image
imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)
found at php.net - imagecreatefrompng under User Contributed Notes
NOT tested
edit see comment
<?php
$bgim_new = imagecreatetruecolor($bgth_width,$bgth_height);
imageantialias($bgim_new,true);
imageAlphaBlending($bgim_new, true);
imageSaveAlpha($bgim_new, true);
?>
After some testing and reading througt several pnp.net comments i've got a working script
<?php
$newImageName = "PNG_transparency_copy.png";
$newWidth = 265;
$newHeight = 150;
$orgAttribs = getimagesize("PNG_transparency_demonstration_1.png");
$orginal = imagecreatefrompng("PNG_transparency_demonstration_1.png");
imagesavealpha($orginal, true);
$newPng = imagecreatetruecolor($newWidth,$newHeight);
imagealphablending($newPng, false);
$color = imagecolortransparent($newPng, imagecolorallocatealpha($newPng, 0, 0, 0, 127));
imagefill($newPng, 0, 0, $color);
imagesavealpha($newPng, true);
imagecopyresampled($newPng,$orginal,0,0,0,0,$newWidth,$newHeight, $orgAttribs[0], $orgAttribs[1]);
header("Content-type: image/png");
imagepng($newPng,$newImageName);
PNG taken from Wikipedia
Try This Function....
<?php
function CropImg($img_dst, $img_src, $dst_width = 300, $dst_height = 180){
$ext = pathinfo($img_src, PATHINFO_EXTENSION);
if($ext != 'jpg' and $ext != 'jpeg'){
$image = imagecreatefrompng($img_src);
}else{
$image = imagecreatefromjpeg($img_src);
}
$filename = $img_dst;
$thumb_width = $dst_width;
$thumb_height = $dst_height;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
if($ext == 'png'){
imagealphablending($thumb, false);
$white = imagecolorallocatealpha($thumb, 0, 0, 0, 127); //FOR WHITE BACKGROUND
imagefilledrectangle($thumb,0,0,$thumb_width,$thumb_height,$white);
imagesavealpha($thumb, true);
}
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
if($ext == 'png'){
imagepng($thumb, $filename);
}else{
imagejpeg($thumb, $filename, 80);
}
return true;
}
CropImg("photo.png", "result.png", 300, 180);
?>