PHP Post to Self with $_FILES - php

This code is not posting anything, anywhere. Its not my upload script, it was taken from
http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html
It works fine as long as I put an external file in the form action field, with these two functions inside it. But why wont it work as a post to self?
<form action="" method="post" encytype="multipart/form-data">
Upload an image for processing<br>
<input type="file" name="Image1"><br>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_POST['submit'])) {
$result = process_image_upload('Image1');
if ($result === false) {
echo '<br>An error occurred while processing upload';
} else {
echo '<br>Uploaded image saved as ' . $result[0];
echo '<br>Thumbnail image saved as ' . $result[1];
}
}
/*
* PHP function to resize an image maintaining aspect ratio
* http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html
*
* Creates a resized (e.g. thumbnail, small, medium, large)
* version of an image file and saves it as another file
*/
define('THUMBNAIL_IMAGE_MAX_WIDTH', 150);
define('THUMBNAIL_IMAGE_MAX_HEIGHT', 150);
function generate_image_thumbnail($source_image_path, $thumbnail_image_path)
{
list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
switch ($source_image_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_image_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_image_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_image_path);
break;
}
if ($source_gd_image === false) {
return false;
}
$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
$thumbnail_image_width = $source_image_width;
$thumbnail_image_height = $source_image_height;
} elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
$thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
$thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
} else {
$thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
$thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
}
$thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
imagedestroy($source_gd_image);
imagedestroy($thumbnail_gd_image);
return true;
}
/*
* Uploaded file processing function
*/
define('UPLOADED_IMAGE_DESTINATION', './images/');
define('THUMBNAIL_IMAGE_DESTINATION', './thumbnails/');
function process_image_upload($field)
{
$temp_image_path = $_FILES[$field]['tmp_name'];
$temp_image_name = $_FILES[$field]['name'];
list(, , $temp_image_type) = getimagesize($temp_image_path);
if ($temp_image_type === NULL) {
return false;
}
switch ($temp_image_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;
move_uploaded_file($temp_image_path, $uploaded_image_path);
$thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION . preg_replace('{\\.[^\\.]+$}', '.jpg', $temp_image_name);
$result = generate_image_thumbnail($uploaded_image_path, $thumbnail_image_path);
return $result ? array($uploaded_image_path, $thumbnail_image_path) : false;
}

This is not working because there are no $_POST["submit"] defined. This means that the script isn't getting past if (isset($_POST['submit']))
Change this line:
<input type="submit" value="Upload">
to this:
<input type="submit" name="submit" value="Upload">

Related

Upload multiple images using PHP class

I need to inquire that i am using PHP class to upload single image. below I have the class and PHP code to upload image. it is working fine for single image upload, and Now I want to upload multiple image using the same class, I used for loop for this purpose and it gives some error. please brief where i am doing wrong
HTML for multiple images
<input type="file" name="photo[]" placeholder="Photo">
code for multiple images
for($i=0;$i<$count;$i++ ) {
if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
$uploadImage = new UploadImage;
echo $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
}
}
Below code is for single image upload which is working fine.
HTML
<input type="file" name="photo" placeholder="Photo">
code
if(isset($_FILES['photo']['tmp_name']) && ($_FILES['photo']['tmp_name']!="")){
$uploadImage = new UploadImage;
$obj['image'] = $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
}
Class.php
<?php
class UploadImage {
public function upload($imageField, $imageFieldIndex = null, $strLargePath = null, $largeWidth = 0, $largeHeight = 0, $strThumbPath = null, $thumbWidth = 0, $thumbHeight = 0)
{
$noLarge = false;
$noThumb = false;
if(empty($strLargePath)) {
$noLarge = true;
}
if(empty($strThumbPath)) {
$noThumb = true;
}
echo $fileName = isset($imageFieldIndex) ? stripslashes($_FILES[$imageField]['name'][$imageFieldIndex]) : stripslashes($_FILES[$imageField]['name']);
$fileTempName = isset($imageFieldIndex) ? $_FILES[$imageField]['tmp_name'][$imageFieldIndex] : $_FILES[$imageField]['tmp_name'];
$extension = $this->getExtension($fileName);
$imageName = time().$imageFieldIndex.'.'.$extension;
if($noLarge == false) {
$this->resize($largeWidth, $largeHeight, $fileTempName, $imageName, $strLargePath);
}
if($noThumb == false) {
$this->resize($thumbWidth, $thumbHeight,$fileTempName, $imageName, $strThumbPath);
}
return $imageName;
}
private function getExtension($strInput)
{
$i = strrpos($strInput,".");
if (!$i){return null;}
$j = strlen($strInput) - $i;
$output = substr($strInput, $i + 1, $j);
return $output;
}
private function resize($newWidth, $newHeight, $imageTempName, $imageName, $savePath) {
$image = new ResizeImage;
$image->newWidth = $newWidth;
$image->newHeight = $newHeight;
$image->imageTempName = $imageTempName; // Full Path to the file
$image->ratio = true; // Keep Aspect Ratio?
// Name of the new image (optional) - If it's not set a new will be added automatically
$image->imageName = substr($imageName, 0, strrpos($imageName, '.'));
/* Path where the new image should be saved. If it's not set the script will output the image without saving it */
$image->savePath = $savePath;
$process = $image->resize();
if($process['result'] && $image->savePath)
{
//echo 'The new image ('.$process['new_file_path'].') has been saved.';
}
}
}
/*-------------------------------- Image resize Class -----------------------------------------*/
class ResizeImage {
var $imageTempName;
var $newWidth;
var $newHeight;
var $ratio;
var $imageName;
var $savePath;
function resize(){
if(!file_exists($this->imageTempName)){
exit("File ".$this->imageTempName." does not exist.");
}
$info = GetImageSize($this->imageTempName);
if(empty($info)){
exit("The file ".$this->imageTempName." doesn't seem to be an image.");
}
$width = $info[0];
$height = $info[1];
$mime = $info['mime'];
/* Keep Aspect Ratio? */
$this->ratio = true;
if($this->ratio){
$thumb = ($this->newWidth < $width && $this->newHeight < $height) ? true : false; // Thumbnail
$largeImage = ($this->newWidth >= $width || $this->newHeight >= $height) ? true : false; // Large Image
if($thumb){
if($this->newWidth > $this->newHeight){
$x = ($width / $this->newWidth);
$this->newHeight = ($height / $x);
}else {
$x = ($height / $this->newHeight);
$this->newWidth = ($width / $x);
}
}else if($largeImage){
if($this->newWidth >= $width){
$x = ($this->newWidth / $width);
$this->newHeight = ($height * $x);
}
else if($this->newHeight >= $height){
$x = ($this->newHeight / $height);
$this->newWidth = ($width * $x);
}
}
}
// What sort of image?
$type = substr(strrchr($mime, '/'), 1);
switch ($type){
case 'jpeg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
break;
case 'jpg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
break;
case 'png':
$image_create_func = 'ImageCreateFromPNG';
$image_save_func = 'ImagePNG';
$newImageExt = 'png';
break;
case 'bmp':
$image_create_func = 'ImageCreateFromBMP';
$image_save_func = 'ImageBMP';
$newImageExt = 'bmp';
break;
case 'gif':
$image_create_func = 'ImageCreateFromGIF';
$image_save_func = 'ImageGIF';
$newImageExt = 'gif';
break;
case 'vnd.wap.wbmp':
$image_create_func = 'ImageCreateFromWBMP';
$image_save_func = 'ImageWBMP';
$newImageExt = 'bmp';
break;
case 'xbm':
$image_create_func = 'ImageCreateFromXBM';
$image_save_func = 'ImageXBM';
$newImageExt = 'xbm';
break;
default:
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
}
// New Image
$image_c = imagecreatetruecolor($this->newWidth, $this->newHeight);
$newImage = $image_create_func($this->imageTempName);
imagealphablending($image_c, false);
imagesavealpha($image_c,true);
$transparent = imagecolorallocatealpha($image_c, 255, 255, 255, 127);
imagefilledrectangle($image_c, 0, 0, $this->newWidth, $this->newHeight, $transparent);
ImageCopyResampled($image_c, $newImage, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height);
if($this->savePath)
{
if($this->imageName)
{
$new_name = $this->imageName.'.'.$newImageExt;
}
else
{
$new_name = $this->newImageName(basename($this->imageTempName)).'_resized.'.$newImageExt;
}
$save_path = $this->savePath.$new_name;
}
else
{
/* Show the image without saving it to a folder */
header("Content-Type: ".$mime);
$image_save_func($image_c);
$save_path = '';
}
$process = $image_save_func($image_c, $save_path);
return array('result' => $process, 'new_file_path' => $save_path);
}
function newImageName($filename)
{
$string = trim($filename);
$string = strtolower($string);
$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
$string = ereg_replace("[ \t\n\r]+", "_", $string);
$string = str_replace(" ", '_', $string);
$string = ereg_replace("[ _]+", "_", $string);
return $string;
}
}
?>
Add the image index to the upload function
for($i=0;$i<$count;$i++ ) {
if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
$uploadImage = new UploadImage;
echo $uploadImage->upload('photo', $i, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
//...................................^ here
}
}
I think this is the way it can be done.
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
And for the script you can upload multiple files using array.
Array
(
[0] => Array
(
[name] => foo.txt
[type] => text/plain
[tmp_name] => /tmp/phpYzdqkD
[error] => 0
[size] => 123
)
[1] => Array
(
[name] => bar.txt
[type] => text/plain
[tmp_name] => /tmp/phpeEwEWG
[error] => 0
[size] => 456
)
)
A quick function that would convert the $_FILES array to the cleaner (IMHO) array.
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
?>
Now I can do the following:
<?php
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
?>
Head over here for more explanation.

exif data, php uploaded image rotation

I'm having a hard time implemeting the php code will ensure that all uploaded photos will be oriented correctly upon upload.
here is my upload.php function ...
function process_image_upload($field)
{
if(!isset($_FILES[$field]['tmp_name']) || ! $_FILES[$field]['name'])
{
return 'empty';
}
$temp_image_path = $_FILES[$field]['tmp_name'];
$temp_image_name = $_FILES[$field]['name'];
list($iwidth, $iheight, $temp_image_type) =
getimagesize($temp_image_path);
if ($temp_image_type === NULL) {
return false;
}
elseif( $iwidth < 400 )
return 'size';
switch ($temp_image_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;
move_uploaded_file($temp_image_path, $uploaded_image_path);
$thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION .
preg_replace('{\\.[^\\.]+$}', '.jpg', $temp_image_name);
$main_image_path = MAIN_IMAGE_DESTINATION . preg_replace('{\\.[^\\.]+$}', '.jpg', $temp_image_name);
$result =
generate_image_thumbnail($uploaded_image_path,
$thumbnail_image_path,150,150
); if( $result )
$result =
generate_image_thumbnail($uploaded_image_path,$main_image_path,400,400,
true);
return $result ? array($uploaded_image_path, $thumbnail_image_path) :
false;
}
if(isset($_POST['upload'])):
$result = process_image_upload('image');
if ($result === false) {
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>An error occurred while processing upload</p></div>');
} else if( $result === 'empty')
{
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>Please select a Image file</p></div>');
}
elseif( $result === 'size')
{
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>Image width must be greater than 400px;</p></div>');
}
else {
update_option('meme_message','<div style="margin-left:0;"
class="updated"><p>Image uploaded successfully</p></div>');
$guploaderr = false;
$count = intval(get_option('meme_image_count'));
update_option('meme_image_count', $count+1);
}
endif;
and here is some php that I know will work to rotate... but I don't know how to implement.
<?php
$image =
imagecreatefromstring(file_get_contents($_FILES['image_upload']
['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$image = imagerotate($image,90,0);
break;
case 3:
$image = imagerotate($image,180,0);
break;
case 6:
$image = imagerotate($image,-90,0);
break;
}
}
// $image now contains a resource with the image oriented correctly
?>

Scaling watermark on image with PHP

i am working on php function that would put watermark on image. I´ve got it working but i need to scale this watermark so the height of the watermark will be 1/3 of the original image. I can do that, but when i put it into my code it just doesnt work, because the parameter of imagecopymerge must be resource, which i dont know what means.
define('WATERMARK_OVERLAY_IMAGE', 'watermark.png');
define('WATERMARK_OVERLAY_OPACITY', 100);
define('WATERMARK_OUTPUT_QUALITY', 100);
function create_watermark($source_file_path, $output_file_path)
{
list($source_width, $source_height, $source_type) = getimagesize($source_file_path);
if ($source_type === NULL) {
return false;
}
switch ($source_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_file_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_file_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_file_path);
break;
default:
return false;
}
$overlay_gd_image = imagecreatefrompng(WATERMARK_OVERLAY_IMAGE);
$overlay_width = imagesx($overlay_gd_image);
$overlay_height = imagesy($overlay_gd_image);
//THIS PART IS WHAT SHOULD RESIZE THE WATERMARK
$source_width = imagesx($source_gd_image);
$source_height = imagesy($source_gd_image);
$percent = $source_height/3/$overlay_height;
// Get new sizes
$new_overlay_width = $overlay_width * $percent;
$new_overlay_height = $overlay_height * $percent;
// Load
$overlay_gd_image_resized = imagecreatetruecolor($new_overlay_width, $new_overlay_height);
// Resize
$overlay_gd_image_complet = imagecopyresized($overlay_gd_image_resized, $overlay_gd_image, 0, 0, 0, 0, $new_overlay_width, $new_overlay_height, $overlay_width, $overlay_height);
//ALIGN BOTTOM, RIGHT
if (isset($_POST['kde']) && $_POST['kde'] == 'pravo') {
imagecopymerge(
$source_gd_image,
$overlay_gd_image_complet,
$source_width - $new_overlay_width,
$source_height - $new_overlay_height,
0,
0,
$new_overlay_width,
$new_overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
if (isset($_POST['kde']) && $_POST['kde'] == 'levo') {
//ALIGN BOTTOM, LEFT
imagecopymerge(
$source_gd_image,
$overlay_gd_image,
0,
$source_height - $overlay_height,
0,
0,
$overlay_width,
$overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
imagejpeg($source_gd_image, $output_file_path, WATERMARK_OUTPUT_QUALITY);
imagedestroy($source_gd_image);
imagedestroy($overlay_gd_image);
imagedestroy($overlay_gd_image_resized);
}
/*
* Uploaded file processing function
*/
define('UPLOADED_IMAGE_DESTINATION', 'originals/');
define('PROCESSED_IMAGE_DESTINATION', 'images/');
function process_image_upload($Field)
{
$temp_file_path = $_FILES[$Field]['tmp_name'];
/*$temp_file_name = $_FILES[$Field]['name'];*/
$temp_file_name = md5(uniqid(rand(), true)) . '.jpg';
list(, , $temp_type) = getimagesize($temp_file_path);
if ($temp_type === NULL) {
return false;
}
switch ($temp_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_file_path = UPLOADED_IMAGE_DESTINATION . $temp_file_name;
$processed_file_path = PROCESSED_IMAGE_DESTINATION . preg_replace('/\\.[^\\.]+$/', '.jpg', $temp_file_name);
move_uploaded_file($temp_file_path, $uploaded_file_path);
$result = create_watermark($uploaded_file_path, $processed_file_path);
if ($result === false) {
return false;
} else {
return array($uploaded_file_path, $processed_file_path);
}
}
$result = process_image_upload('File1');
if ($result === false) {
echo '<br>An error occurred during file processing.';
} else {
/*echo '<br>Original image saved as ' . $result[0] . '';*/
echo '<br>Odkaz na obrazek je zde';
echo '<br><img src="' . $result[1] . '" width="500px">';
echo '<br><div class="fb-share-button" data-href="' . $result[1] . '" data-type="button"></div>';
}

PHP PNG Photo upload that keeps transparency

I'm completely stumpted on this one... I need a photo upload script that keeps the transparency of png files. At the moment the transparent areas are black. Any help is greatly appreciated. Here is my code:
if(isset($_POST)) {
require_once('siteInfo.php');
session_start();
$ThumbSquareSize = 90;
$BigImageMaxSize = $_POST['size'];
$ThumbPrefix = "thumb_";
$DestinationDirectory = '../Uploads/';
$Quality = 100;
if (!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name'])) {
die('Please select a file.');
}
$RandomNumber = rand(0, 9999999999);
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageSize = $_FILES['ImageFile']['size'];
$TempSrc = $_FILES['ImageFile']['tmp_name'];
$ImageType = $_FILES['ImageFile']['type'];
switch (strtolower($ImageType)) {
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
// die('Unsupported file format. Please upload a PNG, GIF, or JPG file.'); //output error and exit
}
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
if (resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)) {
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType)) {
echo 'Error Creating thumbnail';
}
$query = "Update Content set ".$_POST['field']."='".$NewImageName."' WHERE ID=".$_POST['ID'];
mysqli_query($dbc, $query);
mysqli_close($dbc);
echo 'Uploaded file: <span>'.$NewImageName.'</span>.';
} else {
die('Resize Error');
}
}
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType) {
if ($CurWidth <= 0 || $CurHeight <= 0) {
return false;
}
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
if (imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight)) {
switch(strtolower($ImageType)) {
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if (is_resource($NewCanves)) { imagedestroy($NewCanves); }
return true;
}
}
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType){
if ($CurWidth <= 0 || $CurHeight <= 0) {
return false;
}
if ($CurWidth>$CurHeight) {
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
} else {
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if (imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)) {
switch(strtolower($ImageType)) {
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if (is_resource($NewCanves)) { imagedestroy($NewCanves); }
return true;
}
}
I added the following to the "resizeImage" function:
imagealphablending($NewCanves, false);
imagesavealpha($NewCanves, true);
imagealphablending($SrcImage, true);
And that fixed the problem.

I am getting black background image while uploading png image with trransperent

I am getting black background image while uploading png image with transparent.Can u help me
My code is pasted here
$temp_image_path = $_FILES['img_recipe']['tmp_name'];
$temp_image_name = $_FILES['img_recipe']['name'];
$img_arr = getimagesize( $temp_image_path );
$ext = '';
switch($img_arr['mime'])
{
case 'image/gif': $ext = 'gif'; break;
case 'image/png': $ext = 'png'; break;
case 'image/jpeg': $ext = 'jpg'; break;
case 'image/pjpeg': $ext = 'jpg'; break;
case 'image/x-png': $ext = 'png'; break;
default: return false;
}
$temp_image_name = genToken( $len = 32, $md5 = true );
$temp_image_name .= "." . $ext;
$uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;
move_uploaded_file( $temp_image_path, $uploaded_image_path );
$recipe_image_path = RECIPE_IMAGE_DESTINATION . $temp_image_name;
$recipe_thumb_image_path = RECIPE_THUMB_IMAGE_DESTINATION . $temp_image_name;
$result_recipe = generate_image_resize( $uploaded_image_path, $recipe_image_path, RECIPE_MAX_WIDTH, RECIPE_MAX_HEIGHT );
$result_recipe_thumb = generate_image_resize( $uploaded_image_path, $recipe_thumb_image_path, RECIPE_THUMB_MAX_WIDTH, RECIPE_THUMB_MAX_HEIGHT );
unlink($uploaded_image_path);
function generate_image_resize( $source_image_path, $thumbnail_image_path, $width, $height )
{
list( $source_image_width, $source_image_height, $source_image_type ) = getimagesize( $source_image_path );
switch ( $source_image_type )
{
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif( $source_image_path );
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg( $source_image_path );
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng( $source_image_path );
break;
}
if ( $source_gd_image === false ){ return false; }
$thumbnail_image_width = $width;
$thumbnail_image_height = $height;
$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = $thumbnail_image_width / $thumbnail_image_height;
if ( $source_image_width <= $thumbnail_image_width && $source_image_height <= $thumbnail_image_height )
{ $thumbnail_image_width = $source_image_width; $thumbnail_image_height = $source_image_height; }
elseif ( $thumbnail_aspect_ratio > $source_aspect_ratio )
{ $thumbnail_image_width = ( int ) ( $thumbnail_image_height * $source_aspect_ratio ); }
else
{ $thumbnail_image_height = ( int ) ( $thumbnail_image_width / $source_aspect_ratio ); }
$thumbnail_gd_image = imagecreatetruecolor( $thumbnail_image_width, $thumbnail_image_height );
imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height );
imagejpeg( $thumbnail_gd_image, $thumbnail_image_path, 90 );
imagedestroy( $source_gd_image );
imagedestroy( $thumbnail_gd_image );
return true;
}
Lets call source image $si, thumbnail $ti (so long...)
Enable transparency in loaded images :
imagealphablending($si, true);
Get the original transparent color of the loaded image :
$tc = imagecolortransparent($si);
$tc = ($tc != -1)? $tc = imagecolorsforindex($si, $tc):'hopeless';
This creates a black one:
$ti = imagecreatetruecolor( $ti_width, $ti_height );
Then after creating that:
if($tc !='hopeless'){ // do we have transparent color?
// calculate new transparent color
$tn = imagecolorallocate( $ti, $tc['red'], $tc['green'],$tc['blue']);
// we need it as index from now on
$tn = imagecolortransparent( $ti, $tn );
// fill target with transparent color
imagefill( $ti, 0,0, $tn);
// assign the transparent color in target
imagecolortransparent( $ti, $tn );
}
Now a resample may change color indexes on the original image. So artefacts will exist.
imagecopyresampled($ti,$si, 0,0,0,0,$ti_width,$ti_height,$si_width,$si_height );
Add Image Transparency Code Between these two lines:
$thumbnail_gd_image = imagecreatetruecolor( $thumbnail_image_width, $thumbnail_image_height );
imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0,$thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height );
SO new code will be:
$thumbnail_gd_image = imagecreatetruecolor( $thumbnail_image_width, $thumbnail_image_height );
// preserve transparency
if($ext = 'gif' || $ext = 'png')
{
imagecolortransparent($thumbnail_gd_image, imagecolorallocatealpha($thumbnail_gd_image, 0, 0, 0, 127));
imagealphablending($thumbnail_gd_image, false);
imagesavealpha($thumbnail_gd_image, true);
}
imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height );
I don't have an answer (I think #Ihson alreay gave it), but an advice.
Instead of :
switch ($img_arr['mime'])
{
case 'image/gif': $ext = 'gif';
break;
case 'image/png': $ext = 'png';
break;
case 'image/jpeg': $ext = 'jpg';
break;
case 'image/pjpeg': $ext = 'jpg';
break;
case 'image/x-png': $ext = 'png';
break;
default: return false;
}
// (...)
switch ($source_image_type)
{
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_image_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_image_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_image_path);
break;
}
I suggest you to use :
$string = file_get_contents($source_image_path);
$img = #imagecreatefromstring($string);
if ($img === false) {
// something went wrong...
} else {
// do what you want with $img
}
This is discusting to use # operator, but in this case, there is at least 2 reasons :
less code to write / to test / to maintain
mime type may be wrong (if I rename a .jpg as a .png).

Categories