PHP - Reuso de funciones

 
Vista:

Reuso de funciones

Publicado por Luis Armando (6 intervenciones) el 02/10/2009 01:29:52
Hola!
Tengo un problema con un script en php que sirve para subir archivos a mi sitio y estoy adaptando uno que tengo escrito en perl (funciona) a php pero me encuentro con una subrutina de perl que la tengo que pasar a function en php y no me funciona igual. Para ser mas claro arme un ejemplo simple en php:
<?php
$tipo = 2;
$factor = 6;
$filename = enc_suport($tipo,$factor);
echo "esto es $filename \n";
function enc_suport($a, $b) {
$result = $a + $b;
if($result >= 20) {
return $result;
} else {
enc_suport($a,$result);
}
}
?>
la funcion enc_suport se encarga de controlar que el valor a pasar sea igual o mayor que 20, si no es asi ejecuta nuevamente la funcion hasta que termine, !pero no me retorna nada!, en cambio lo mismo escrito en perl (en este caso seria una subrutina) si funcionaria, se puede reusar la subrutina.
¿Cómo podria solucionar esto?.
Gracias
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Reuso de funciones

Publicado por Diego Romero (1450 intervenciones) el 02/10/2009 09:02:24
Pues...

function enc_suport($a, $b, &$result) {
$result = $a + $b;
if($result < 20) {
enc_suport($a,$result,$result);
}
}
$tipo = 2;
$factor = 6;
enc_suport($tipo,$factor,$filename);
echo "esto es $filename <br>\n";

Sin embargo para hacer lo que quieres no era necesario recurrir a la recursión, bastaba con hacer:

$filename = $factor;
while ($filename < 20)
{
$filename = $tipo + $filename;
}

O, si lo quieres en una función:

function enc_suport2($a, $b) {
while ($a < 20)
{
$a = $a + $b;
}
return $a;
}

$filename = enc_suport2($tipo,$factor);
echo "2: esto es $filename <br>\n";
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Reuso de funciones

Publicado por Luis Armando (6 intervenciones) el 03/10/2009 00:36:40
Bien Gracias! Diego, ya arme el script y funciona, pero me encuentro con otra sorpresa, esta ves si paso las rutinas:
Pagina index.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>PHP AJAX Image Upload, Truly Web 2.0!</title>
<meta name="description" content="PHP AJAX Image Upload, Truly Web 2.0!" />
<meta name="keywords" content="PHP AJAX Image Upload, Truly Web 2.0!" />
<meta name="robots" content="index,follow" />
<meta name="revisit-after" content="10 days" />
<meta name="author" content="AT Web Results, Inc. - http://www.selfpropiedades.com" />
<meta name="copyright" content="AT Web Results, Inc." />
<meta name="distribution" content="global" />
<meta name="resource-type" content="document" />
<link href="css/styles.css" rel="stylesheet" type="text/css" media="all" />
<!-- MAKE SURE TO REFERENCE THIS FILE! -->
<script type="text/javascript" src="scripts/ajaxupload.js"></script>
<!-- END REQUIRED JS FILES -->
</head>
<body>

<div id="container">
</strong> are always <strong>appreciated</strong>, see the link below.</p>

<br />
<!-- THIS IS THE IMPORTANT STUFF! -->
<div id="demo_area">
<div id="left_col">
<fieldset>
<legend>Standard Use</legend>
<form action="scripts/ajaxupload.php?filename=name&maxSize=9999999999&maxW=200&fullPath=http://127.0.0.1/ajax_image_upload/uploads/&relPath=../uploads/&colorR=255&colorG=255&colorB=255&maxH=300" method="post">
<p><input type="file" name="name" /></p>
<!--
ajaxUpload fields
1. form - the form to submit or the ID of a form .
2. url_action - url to submit the form. like 'action' parameter of forms.
3. id_element - element that will receive return of upload.
4. html_show_loading - Text (or image) that will be show while loading
5. html_error_http - Text (or image) that will be show if HTTP error.
-->
<p><button onclick="ajaxUpload(this.form,'scripts/ajaxupload.php?filename=name&maxSize=9999999999&maxW=150&fullPath=http://127.0.0.1/ajax_image_upload/uploads/&relPath=../uploads/&colorR=255&colorG=255&colorB=255&maxH=300','upload_area','File Uploading Please Wait...<br /><img src=\'images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' />','<img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /> Error in Upload, check settings and path info in source code.'); return false;" type="button">Upload Image</button></p>
</form>
</fieldset>
<fieldset>
<legend>Sleeker More "Web 2.0" onChange Use</legend>
<form action="scripts/ajaxupload.php?filename=name&maxSize=9999999999&maxW=200&fullPath=http://127.0.0.1/ajax_image_upload/uploads/&relPath=../uploads/&colorR=255&colorG=255&colorB=255&maxH=300" method="post">
<p><input type="file" name="name" onchange="ajaxUpload(this.form,'scripts/ajaxupload.php?filename=name&maxSize=9999999999&maxW=500&fullPath=http://127.0.0.1/ajax_image_upload/uploads/&relPath=../uploads/&colorR=255&colorG=255&colorB=255&maxH=500','upload_area','File Uploading Please Wait...<br /><img src=\'images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' />','<img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /> Error in Upload, check settings and path info in source code.'); return false;" /></p>
</form>
</fieldset>
<fieldset>
<legend>Unobtrusive (Falls Back to a Standard Form)</legend>
<form action="scripts/ajaxupload.php?filename=name&maxSize=9999999999&maxW=200&fullPath=http://127.0.0.1/ajax_image_upload/uploads/&relPath=../uploads/&colorR=255&colorG=255&colorB=255&maxH=300" method="post">
<p><input type="file" name="name" onchange="ajaxUpload(this.form,'scripts/ajaxupload.php?filename=name&maxSize=9999999999&maxW=500&fullPath=http://127.0.0.1/ajax_image_upload/uploads/&relPath=../uploads/&colorR=255&colorG=255&colorB=255&maxH=500','upload_area1','File Uploading Please Wait...<br /><img src=\'images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' />','<img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /> Error in Upload, check settings and path info in source code.'); return false;" /></p>
<noscript><p><button type="submit">Upload Image</button></p></noscript>
</form>
</fieldset>
<br /><small style="font-weight: bold; font-style:italic;">Supported File Types: gif, jpg, png</small>
</div>
<div id="right_col">
<div id="upload_area">
Images Will Be uploaded here for the demo.<br /><br />
You can direct them to do any thing you want!
</div>
<div id="upload_area1">
Images Will Be uploaded here for the demo.<br /><br />
You can direct them to do any thing you want!
</div>
Help Spread the Word<br /><br />

</div>
<div class="clear"> </div>
</div>
<!-- END IMPORTANT STUFF -->
<p style="text-align:center;">Compatible with all of today's popular browsers, including webkit browsers such as: Google Chrome and Safari. Also this has been tested with MooTools 1.1 and 1.2, Prototype, jQuery and no comparability issues were found!<br />
<br /><img src="images/browsers.jpg" width="448" height="100" alt="AJAX Image Upload Browser compatibility" /></p>
Pretty Cool, huh? Well kids I promised the source code for the perfect AJAX / PHP style image uploader. Please visit the forum for download and credits <a href="http://atwebresults.com/forum/viewtopic.php?f=25&t=391" title="Download">Click Here</a><br /><br />
<p><a rel="license" href="http://creativecommons.org/licenses/by/3.0/us/"><img alt="Creative Commons License" style="border-width:0; float:left; margin-right: 20px;margin-top:4px;" src="http://creativecommons.org/images/public/somerights20.png" /></a><small>PHP AJAX Image Upload Revealed by <a xmlns:cc="http://creativecommons.org/ns#" href="http://atwebresults.com/ajax_image_upload/" rel="cc:attributionURL">Tim Wickstrom</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/us/">Creative Commons Attribution 3.0 United States License</a>. Based on a work at <a xmlns:dc="http://purl.org/dc/elements/1.1/" href="http://atwebresults.com/ajax_image_upload/" rel="dc:source">atwebresults.com</a></small></p>
<br />

<br /><br /><br />
</div>
<div id="footer">© <?php $firstyr = 2005; $nextyr = date('Y'); if($nextyr <= $firstyr){ echo $firstyr; }else echo "$firstyr - $nextyr"; ?>, AT Web Results, Inc. - Using 100% W3C Valid <a href="http://validator.w3.org/check?uri=referer">xHTML {STRICT}</a> - <a href="http://jigsaw.w3.org/css-validator/check?uri=referer">CSS</a></div>
<div style="position: fixed; right: 5px; bottom: 65px;"><img src="images/webbadge.gif" width="150" height="150" alt="Web 2.0" /></div>
</body>
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Reuso de funciones

Publicado por Luis Armando (6 intervenciones) el 03/10/2009 00:40:40
pagina ajaxupload.php:
<?php
function uploadImage($fileName, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH = null){
$folder = $relPath;
$maxlimit = $maxSize;
$allowed_ext = "jpg,jpeg,gif,png,bmp";
$match = "";
$filesize = $_FILES[$fileName]['size'];
if($filesize > 0){
$filename = strtolower($_FILES[$fileName]['name']);
$filename = preg_replace('/\s/', '_', $filename);
if($filesize < 1){
$errorList[] = "File size is empty.";
}
if($filesize > $maxlimit){
$errorList[] = "File size is too big.";
}
$file_ext = preg_split("/\./",$filename);
$allowed_ext = preg_split("/\,/",$allowed_ext);
foreach($allowed_ext as $ext){
if($ext==end($file_ext)){
$match = "1"; // File is allowed
$fileImg ="TM1.$ext";
// $NUM = time();
// $front_name = substr($file_ext[0], 0, 15);
$newfilename = check_existence($folder, $fileImg, $newnum);
// $newfilename = $front_name."_".$NUM.".".end($file_ext);
$filetype = end($file_ext);
$save = $folder.$newfilename;
if(!file_exists($save)){
list($width_orig, $height_orig) = getimagesize($_FILES[$fileName]['tmp_name']);
if($maxH == null){
if($width_orig < $maxW){
$fwidth = $width_orig;
}else{
$fwidth = $maxW;
}
$ratio_orig = $width_orig/$height_orig;
$fheight = $fwidth/$ratio_orig;

$blank_height = $fheight;
$top_offset = 0;

}else{
if($width_orig <= $maxW && $height_orig <= $maxH){
$fheight = $height_orig;
$fwidth = $width_orig;
}else{
if($width_orig > $maxW){
$ratio = ($width_orig / $maxW);
$fwidth = $maxW;
$fheight = ($height_orig / $ratio);
if($fheight > $maxH){
$ratio = ($fheight / $maxH);
$fheight = $maxH;
$fwidth = ($fwidth / $ratio);
}
}
if($height_orig > $maxH){
$ratio = ($height_orig / $maxH);
$fheight = $maxH;
$fwidth = ($width_orig / $ratio);
if($fwidth > $maxW){
$ratio = ($fwidth / $maxW);
$fwidth = $maxW;
$fheight = ($fheight / $ratio);
}
}
}
if($fheight == 0 || $fwidth == 0 || $height_orig == 0 || $width_orig == 0){
die("FATAL ERROR REPORT ERROR CODE [add-pic-line-67-orig] to <a href='http://www.atwebresults.com'>AT WEB RESULTS</a>");
}
if($fheight < 45){
$blank_height = 45;
$top_offset = round(($blank_height - $fheight)/2);
}else{
$blank_height = $fheight;
}
}
$image_p = imagecreatetruecolor($fwidth, $blank_height);
$white = imagecolorallocate($image_p, $colorR, $colorG, $colorB);
imagefill($image_p, 0, 0, $white);
switch($filetype){
case "gif":
$image = @imagecreatefromgif($_FILES[$fileName]['tmp_name']);
break;
case "jpg":
$image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
break;
case "jpeg":
$image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
break;
case "png":
$image = @imagecreatefrompng($_FILES[$fileName]['tmp_name']);
break;
}
@imagecopyresampled($image_p, $image, 0, $top_offset, 0, 0, $fwidth, $fheight, $width_orig, $height_orig);
switch($filetype){
case "gif":
if(!@imagegif($image_p, $save)){
$errorList[]= "PERMISSION DENIED [GIF]";
}
break;
case "jpg":
if(!@imagejpeg($image_p, $save, 100)){
$errorList[]= "PERMISSION DENIED [JPG]";
}
break;
case "jpeg":
if(!@imagejpeg($image_p, $save, 100)){
$errorList[]= "PERMISSION DENIED [JPEG]";
}
break;
case "png":
if(!@imagepng($image_p, $save, 0)){
$errorList[]= "PERMISSION DENIED [PNG]";
}
break;
}
@imagedestroy($filename);
}else{
$errorList[]= "CANNOT MAKE IMAGE IT ALREADY EXISTS";
}
}
}
}else{
$errorList[]= "NO FILE SELECTED";
}
if(!$match){
$errorList[]= "File type isn't allowed: $filename";
}
if(sizeof($errorList) == 0){
return $fullPath.$newfilename;
}else{
$eMessage = array();
for ($x=0; $x<sizeof($errorList); $x++){
$eMessage[] = $errorList[$x];
}
return $eMessage;
}
}

function check_existence($dir,$fileImg,$newnum) {
$exists = 1;
if(!$newnum) $newnum = 0;
$nuevo_jpg = $dir.$fileImg;
if(!file_exists($nuevo_jpg)) $exists = 0;

// es necesario renombrar el archivo y controlar nuevamente si existe
while($exists){
$newnum++;
// verifica la extensión
$file_type = preg_split("/\./", $fileImg); // separa de los puntos
$bareName = $file_type[0];
// la extension es el ultimo elemento de @file_type
$file_ext = end($file_type);
// $#file_ext es el último elemento

// quita todos los números del final de la cadena $bareName
$bareName = preg_replace('/\d/','',$bareName);

// concatena barename + newnum + extension
$fileImg = $bareName . $newnum . '.' . $file_ext;

if(!file_exists($dir.$fileImg)) $exists = 0;
// ejecuta nuevamente la subrutina
}
// ahora no existe el nombre, devuelve el nombre a ser usado
echo "me da: $fileImg";
return $fileImg;
}

$filename = strip_tags($_REQUEST['filename']);
$maxSize = strip_tags($_REQUEST['maxSize']);
$maxW = strip_tags($_REQUEST['maxW']);
$fullPath = strip_tags($_REQUEST['fullPath']);
$relPath = strip_tags($_REQUEST['relPath']);
$colorR = strip_tags($_REQUEST['colorR']);
$colorG = strip_tags($_REQUEST['colorG']);
$colorB = strip_tags($_REQUEST['colorB']);
$maxH = strip_tags($_REQUEST['maxH']);

$filesize_image = $_FILES[$filename]['size'];
if($filesize_image > 0){
$upload_image = uploadImage($filename, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH);
if(is_array($upload_image)){
foreach($upload_image as $key => $value) {
if($value == "-ERROR-") {
unset($upload_image[$key]);
}
}
$document = array_values($upload_image);
for ($x=0; $x<sizeof($document); $x++){
$errorList[] = $document[$x];
}
$imgUploaded = false;
}else{
$imgUploaded = true;
}
}else{
$imgUploaded = false;
$errorList[] = "File Size Empty";
}
?>
<?php
$myArray = explode ("$fullPath", "$upload_image");
$myImageDel = $relPath.$myArray[1];
$mypath = 'http://127.0.0.1/ajax_image_upload/scripts/';
$imgMin = '/ajax_image_upload/uploads/'.$myArray[1].'';
if($imgUploaded){
echo '<iframe id="marco" width="170" height="200" border="0" frameborder="0" src="'.$mypath.'remover.php?imgdel='.$myImageDel.'&imgshow='.$imgMin.'">';
echo '</iframe>';
}else{
echo '<img src="images/error.gif" width="16" height="16px" border="0" style="marin-bottom: -3px;" /> Error(s) Found: ';
foreach($errorList as $value){
echo $value.', ';
}
}
?>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Reuso de funciones

Publicado por Luis Armando (6 intervenciones) el 03/10/2009 00:41:48
pagina remover.php:

<?php
function borrar_imagen($archivo) {
unlink("$archivo");
}

$archivo = strip_tags($_REQUEST['archivo']);
$image_min = strip_tags($_REQUEST['imgshow']);
$myImageDel = strip_tags($_REQUEST['imgdel']);
$link_gd = '/ajax_image_upload';
if(file_exists($archivo)) {
$delete_image = borrar_imagen($archivo);
} else {
echo '<img src="/ajax_image_upload/images/success.gif" width="16" height="16" border="0" style="marin-bottom: -4px;" /> Success!<br /><img src="gd_imager.pl?img='.$image_min.'&base=/ajax_image_upload/scripts/base.png" border="0" />';
echo '<br><CENTER><a href="remover.php?archivo='.$myImageDel.'">Remover</a></CENTER>';
exit;
}

if(file_exists($archivo)) {
echo "<CENTER><B>No se pudo eliminar</B></CENTER>";
} else {
echo"<CENTER><B>Imagen eliminada!</B></CENTER>";
}

?>

ajaxupload.js:

function $m(theVar){
return document.getElementById(theVar)
}
function remove(theVar){
var theParent = theVar.parentNode;
theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
if(obj.addEventListener)
obj.addEventListener(evType, fn, true)
if(obj.attachEvent)
obj.attachEvent("on"+evType, fn)
}
function removeEvent(obj, type, fn){
if(obj.detachEvent){
obj.detachEvent('on'+type, fn);
}else{
obj.removeEventListener(type, fn, false);
}
}
function isWebKit(){
return RegExp(" AppleWebKit/").test(navigator.userAgent);
}
function ajaxUpload(form,url_action,id_element,html_show_loading,html_error_http){
var detectWebKit = isWebKit();
form = typeof(form)=="string"?$m(form):form;
var erro="";
if(form==null || typeof(form)=="undefined"){
erro += "The form of 1st parameter does not exists.\n";
}else if(form.nodeName.toLowerCase()!="form"){
erro += "The form of 1st parameter its not a form.\n";
}
if($m(id_element)==null){
erro += "The element of 3rd parameter does not exists.\n";
}
if(erro.length>0){
alert("Error in call ajaxUpload:\n" + erro);
return;
}
var iframe = document.createElement("iframe");
iframe.setAttribute("id","ajax-temp");
iframe.setAttribute("name","ajax-temp");
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
form.parentNode.appendChild(iframe);
window.frames['ajax-temp'].name="ajax-temp";
var doUpload = function(){
removeEvent($m('ajax-temp'),"load", doUpload);
var cross = "javascript: ";
cross += "window.parent.$m('"+id_element+"').innerHTML = document.body.innerHTML; void(0);";
$m(id_element).innerHTML = html_error_http;
$m('ajax-temp').src = cross;
if(detectWebKit){
remove($m('ajax-temp'));
}else{
setTimeout(function(){ remove($m('ajax-temp'))}, 250);
}
}
addEvent($m('ajax-temp'),"load", doUpload);
form.setAttribute("target","ajax-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
}
gd_imager.pl:

#!/usr/bin/perl

#############################
#
# ReJump DG Imager (web engine version)
#
# Image resizing tool (with cashing possibility)
#
# http://www.rejump.com
# V 1.2
#
# (c) 2003, mas
#
# mail: [email protected]
# [email protected]
#
# Don't remove this, please! ;-)
#
#

use GD;
use CGI;

$cgi = new CGI;
my $img_sub_path = reDot($cgi->param('img'));
my $configFile = $cgi->param('conf');

my $Width, $Height, $dX, $dY, $Border, $Base, $Align, $VAlign;

if( $configFile ne "" )
{
loadConfig($configFile);

$Width = readIntValue('width', 0);
$Height = readIntValue('height', 0);
$dX = readIntValue('dx', 0);
$dY = readIntValue('dy', 0);
$Border = readIntValue('border', -1);
$Base = readValue('base', '');
$Align = readValue('align', 'center');
$VAlign = readValue('valign', 'center');
$Cash_Dir = readValue('cash_dir', '');
$Cash_Time = readIntValue('cash_time', 60*60*24);
$Cash_Slash = readValue('cash_slash', '--');

freeConfig();
}else{
$Width = $cgi->param('width');
$Width+=0;
$Height = $cgi->param('height');
$Height+=0;
$Base = reDot($cgi->param('base'));
$dX = $cgi->param('dx');
$dX+=0;
$dY = $cgi->param('dy');
$dY+=0;
$Border = $cgi->param('border');
if( $Border eq "")
{
$Border=-1;
}
$Border+=0;

$Align = $cgi->param('align');
if( $Align ne "right" && $Align ne "left" )
{
$Align="center";
}
$VAlign = $cgi->param('valign');
if( $VAlign ne "top" && $VAlign ne "botton" )
{
$VAlign="center";
}

}

$img_path=$ENV{'DOCUMENT_ROOT'}.$img_sub_path;

if( $img_path!~/\.jpg/ && $img_path!~/\.jpeg/ && $img_path!~/\.png/ )
{
open(IMG,$img_path);
binmode(IMG);
print "Content-type: image/pjpeg\n\n";
binmode(STDOUT);
while(my $size=sysread(IMG,$buf,10000)){
print $buf;
}
close(IMG);
exit;
}

if( -d $Cash_Dir )
{
$cashed_file_name=$img_sub_path;
$cashed_file_name=~s/\//$Cash_Slash/g;
if( -f $Cash_Dir."/".$cashed_file_name )
{

$cash_time=(stat($Cash_Dir."/".$cashed_file_name))[9];
if($cash_time > $^T - $Cash_Time)
{

open(IMG,$Cash_Dir."/".$cashed_file_name);
binmode(IMG);
print "Content-type: image/pjpeg\n\n";
binmode(STDOUT);
while(my $size=sysread(IMG,$buf,10000)){
print $buf;
}
close(IMG);
exit;
}
}
}

if($Base eq "")
{

if( -f $img_path)
{
$im = newFromJpeg GD::Image($img_path);

($width,$height) = $im->getBounds();

($new_width,$new_height) = newSize($width,$height,$Width,$Height);

$im2 = new GD::Image($new_width,$new_height);
$im2->copyResized($im,0,0,0,0,$new_width,$new_height,$width,$height);

print "Content-type: image/pjpeg\n\n";
binmode(STDOUT);
print $im2->jpeg();
exit;
}else{
print "Content-type: text/html\n\n";
print "Have no image\n";
}

}else{

$base_path=$ENV{'DOCUMENT_ROOT'}.$Base;

# create a new image

if( -f $img_path)
{
$im = newFromJpeg GD::Image($img_path);
($width,$height) = $im->getBounds();
}else{
$im = newFromPng GD::Image($base_path);
print "Content-type: image/pjpeg\n\n";
binmode(STDOUT);
print $im->jpeg();
exit;
}

$im2 = newFromPng GD::Image($base_path);

($width2,$height2) = $im2->getBounds();

if( $Width<=0 && $Height<=0 && Border>=0 )
{
if( $Align eq "center" )
{
$Width=$width2-$Border*2;
}else{
$Width=$width2-$Border;
}
}

($new_width,$new_height) = newSize($width,$height,$Width,$Height);

if( $Align eq "center" )
{
$border_x=$dX+int(($width2-$new_width)/2);
}elsif( $Align eq "left" ){
$border_x=$dX + (($Border>=0) ? $Border : 0);
}elsif( $Align eq "right" ){
$border_x=$width2-$new_width - $dX - (($Border>=0) ? $Border : 0);
}

if( $VAlign eq "center" )
{
$border_y=$dY+int(($height2-$new_height)/2);
}elsif( $VAlign eq "top" ){
$border_y=$dY + (($Border>=0) ? $Border : 0);
}elsif( $Align eq "bottom" ){
$border_y=$height2-$new_height - $dY - (($Border>=0) ? $Border : 0);
}

$im2->copyResized($im,$border_x,$border_y,0,0,$new_width,$new_height,$width,$height);

print "Content-type: image/pjpeg\n\n";

if( -d $Cash_Dir )
{
$cashed_file_name=$img_sub_path;
$cashed_file_name=~s/\//$Cash_Slash/g;
open(CASH,">".$Cash_Dir."/".$cashed_file_name);
binmode(CASH);
print CASH $im2->jpeg();
close(CASH);
}

binmode(STDOUT);
print $im2->jpeg();

}

exit;

sub newSize($$$$)
{
my $width=shift();
my $height=shift();
my $Width=shift();
my $Height=shift();

my $new_width, $new_height;

if($Width<=0 && $Height>0)
{
$Width=10000;
}else{
if($Height<=0 && $Width>0)
{
$Height=10000;
}
}

if($Width<=0 && $Height<=0)
{
return ($width,$height);
}

if($Width/$width > $Height/$height)
{
$new_height=$Height;
$new_width=int(($Height/$height)*$width);
}
if($Width/$width <= $Height/$height)
{
$new_width=$Width;
$new_height=int(($Width/$width)*$height);
}

return ($new_width,$new_height);
}

sub loadConfig($)
{
open(FILE, shift());
@config = <FILE>;
chomp(@config);
close(FILE);
}

sub freeConfig()
{
@config = ();
}

sub readValue($$)
{
$quoted = 1;
my $k = shift();
foreach(@config)
{
if ($_ =~ /^\s*$k\s*=\s*(.+?)\s*$/)
{
$_ = $1;
return $1 if (/^"(.+?)"$/);
$quoted = 0;
return $_;
}
}
$quoted = 0;
return shift();
}

sub readIntValue($$)
{
return int(readValue(shift(), shift()));
}

sub readArray($)
{
my $k = shift();
my $v = readValue($k, '');
return split(/"\s*,\s*"/, $v) if ($quoted);
return split(/\s*,\s*/, $v);
}

sub readIntArray($)
{
my @v = readArray(shift());
foreach(@v)
{
$_ = int($_);
}
return @v;
}

sub reDot($)
{
my $str=shift();
$str=~s/\.\.//g;
return $str;
}

Esto es todo lo que tengo en el directorio de trabajo local. El arbol es el siguiente:

index.html
------- uploads (carpeta donde se grabaran las imagenes)
------- scripts (carpeta de scripts)
ajaxupload.php
remover.php
gd_imager.pl
ajaxupload.js

Puede subir hasta dos imagenes por vez y hay posibilidad de prever la imagen en miniatura mediante el script gd_imager.pl, se pueden borrar las imagenes subidas y nuevamente subir otra. Hasta aqui todo bien pero cuando uno borra la imagen y decide subir otra, el prever es la misma imagen que la anteriormente borrada, cuando debiera ser la nueva imagen, no entiendo porque esto.
Gracias por ayudar
Armando
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Reuso de funciones

Publicado por Diego Romero (1450 intervenciones) el 03/10/2009 02:11:13
Se ve MUY interesante lo que has posteado, no lo he probado aún, pero lo que dices parece ser el típico problema con AJAX: el caché del navegador. Yo suelo solucionarlo pasándole un parámetro aleatorio que fuezar al navegador a cargar la página de resultado en vez de sacarla del caché. Tendría que implementar el código que has puesto para saber si es eso u otra cosa.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Reuso de funciones

Publicado por Luis Armando (6 intervenciones) el 03/10/2009 13:24:03
Aclaro -porque no se ve bien- que los archivos:
ajaxupload.php
remover.php
gd_imager.pl
ajaxupload.js

se encuentran en la carpeta scripts. Ademas me olvidaba que hay un archivo styles.css en una carpeta css:

body {
background-color: #fff;
padding: 0px;
margin: 0px;
color:#000;
font-size: 13px;
line-height: 18px;
font-family:Verdana, Tahoma, Arial, Helvetica, sans-serif;
}
img {
border: 0px;
}
a, a:link, a:visited, a:active {
color: #0099CC;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
h3 {
padding: 0px;
margin: 0px;
font-size: 16px;
}
h2 {
margin: 10px 0px 5px 0px;
padding: 0px;
font-size: 16px;
}
h1 {
padding: 0px;
margin: 12px 0 12px 0;
font-size: 16px;
}
#topblock {
position:relative;
clear:both;
height:210px;
width: 100%;
background-image: url(../images/bg.jpg);
background-repeat: repeat-x;
background-position: left top;
padding-top: 45px;
color: #f1f1f1;
clear:both;
overflow:hidden;
}
#topblock img {
position:absolute;
top:0px;
left: 0px;
}
#topblock h1 {
margin: 0px 0px 32px 130px;
padding: 0px;
font-size: 22px;
line-height: 25px;
font-family: Georgia, "Times New Roman", Times, serif;
}
#topblock p {
position: absolute;
top: 100px;
left: 150px;
right: 100px;
padding: 0px;
margin: 0px;
font-size: 15px;
font-style: italic;
text-align: justify;
}
#topblock p a {
position: absolute;
right: 0px;
}
small {
font-size: 9px;
}
#container {
width: 780px;
margin-left: auto;
margin-right: auto;
text-align:center;
}
#container p {
text-align: justify;
margin: 15px 0px;
padding:0px;
}
#demo_area {
width: 728px;
position:relative;
text-align:left;
margin-left:auto;
margin-right: auto;
}
fieldset {
width: 469px;
padding:0px;
margin: 0px;
border: 1px solid #bbbbbb;
}
legend {
font-weight:bold;
font-size: 14px;
padding: 8px;
margin: 0px 0px 0px 10px;
}
form {
padding: 0;
margin: 15px;
position: relative;
}
fieldset button {
margin-top: 12px;
}
#left_col {
float: left;
margin-right: 25px;
}
#right_col {
margin-top: 16px;
width: 200px;
float: left;
border: 1px solid #bbbbbb;
text-align:center;
padding: 15px;
}
#upload_area {
border-bottom: 1px solid #bbbbbb;
padding-bottom: 15px;
margin-bottom: 15px;
}
.clear {
clear: both;
}
#footer {
display:block;
width:100%;
font-weight:bold;
font-size: 9px;
background-color: #000000;
color: #ffffff;
line-height: 65px;
text-align:center;
}
#download_now {
text-align:center;
margin-top: 10px;
clear: both;
}
#download_now a, #download_now a:active, #download_now a:visited{
margin-left: auto;
margin-right: auto;
color: transparent;
text-indent: -5000px;
overflow: hidden;
display: block;
width: 127px;
height: 25px;
background-image:url(../images/download.jpg);
background-position:top left;
background-repeat:no-repeat;
}
#download_now a:hover {
background-position:bottom left;
}
#donate_now {
text-align:center;
margin-top: 10px;
clear: both;
}
#donate_now a, #donate_now a:active, #donate_now a:visited{
margin-left: auto;
margin-right: auto;
color: transparent;
text-indent: -5000px;
overflow: hidden;
display: block;
width: 127px;
height: 25px;
background-image:url(../images/donations.jpg);
background-position:top left;
background-repeat:no-repeat;
}
#donate_now a:hover {
background-position:bottom left;
}

Ademas el archivo base.png no lo puedo pasar por este medio pero es una imagen en gris de 120 x 120 pixeles ubicada en la carpeta scripts. La parte que no funciona bien se encuentra en el script remover.php en el sector que dice:

} else {
echo '<img src="/ajax_image_upload/images/success.gif" width="16" height="16" border="0" style="marin-bottom: -4px;" /> Success!<br /><img src="gd_imager.pl?img='.$image_min.'&base=/ajax_image_upload/scripts/base.png" border="0" />';
echo '<br><CENTER><a href="remover.php?archivo='.$myImageDel.'">Remover</a></CENTER>';
exit;
}

donde funciona gd_imager.pl. De todas formas lo probe con con algo mas simple en su lugar:

<img src="'.$image_min.'" width="100" border="0" /> y pasa exactamente lo mismo.
Aclaro que todos los archivos y carpetas se encuentra en otra carpeta ajax_image_upload.

Gracias por ayudar Diego.

Luis Armando
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Reuso de funciones

Publicado por Luis Armando (6 intervenciones) el 06/10/2009 17:54:49
Bueno... como nadie me respondio me respondo yo mismo, buscando cosas por algunos sitios y tratando de ser lo mas sintetico posible en las escrituras de los scripts para evitar que no se cargue la misma imagen que se encuentra en el cache de nuestro explorador, hay que tratar de cargar algo disitnto. Por suerte html permite cambiar un parametro de las url que evitan leer el archivo de la cache. En el caso de php podemos hacer lo siguiente:

echo '<img src="'.$image_min.'?21" width="100" border="0" />';

no es lo mismo que:
echo '<img src="'.$image_min.'?23" width="100" border="0" />';

y nos estamos refiriendo a la misma imagen pero fuerza a actualizar la imagen $image_min. Para generalizar esto podemos implementarlo asi:

echo '<img src="'.$image_min.'?'.time().'" width="100" border="0" />';

donde time() es una funcion de php que toma un valor numerico distinto a medida que pasa el tiempo. De esta forma nunca tendremos problemas con la actualizacion de las imagenes.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar