Ajax 上传图片并可以生成指定大小缩略图

Ajax 上传图片并可以生成指定大小缩略图

 
Ajax 上传图片并可以生成指定大小缩略图

 

 

XML/HTML Code
  1. <div id="upload-wrapper">  
  2. <div align="center">  
  3.   
  4. <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">  
  5. <input name="ImageFile" id="imageInput" type="file" />  
  6. <input type="submit"  id="submit-btn" value="Upload" />  
  7. <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>  
  8. </form>  
  9. <div id="output"></div>  
  10. </div>  
  11. </div>  

 

JavaScript Code
  1. <script type="text/javascript">  
  2. $(document).ready(function() {   
  3.     var options = {   
  4.             target:   '#output',   // target element(s) to be updated with server response   
  5.             beforeSubmit:  beforeSubmit,  // pre-submit callback   
  6.             success:       afterSuccess,  // post-submit callback   
  7.             resetForm: true        // reset the form after successful submit   
  8.         };   
  9.           
  10.      $('#MyUploadForm').submit(function() {   
  11.             $(this).ajaxSubmit(options);              
  12.             // always return false to prevent standard browser submit and page navigation   
  13.             return false;   
  14.         });   
  15. });   
  16.   
  17. function afterSuccess()  
  18. {  
  19.     $('#submit-btn').show(); //hide submit button  
  20.     $('#loading-img').hide(); //hide submit button  
  21.   
  22. }  
  23.   
  24. //function to check file size before uploading.  
  25. function beforeSubmit(){  
  26.     //check whether browser fully supports all File API  
  27.    if (window.File && window.FileReader && window.FileList && window.Blob)  
  28.     {  
  29.           
  30.         if( !$('#imageInput').val()) //check empty input filed  
  31.         {  
  32.             $("#output").html("Are you kidding me?");  
  33.             return false  
  34.         }  
  35.           
  36.         var fsize = $('#imageInput')[0].files[0].size; //get file size  
  37.         var ftype = $('#imageInput')[0].files[0].type; // get file type  
  38.           
  39.   
  40.         //allow only valid image file types   
  41.         switch(ftype)  
  42.         {  
  43.             case 'image/png'case 'image/gif'case 'image/jpeg'case 'image/pjpeg':  
  44.                 break;  
  45.             default:  
  46.                 $("#output").html("<b>"+ftype+"</b> Unsupported file type!");  
  47.                 return false  
  48.         }  
  49.           
  50.         //Allowed file size is less than 1 MB (1048576)  
  51.         if(fsize>1048576)   
  52.         {  
  53.             $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");  
  54.             return false  
  55.         }  
  56.                   
  57.         $('#submit-btn').hide(); //hide submit button  
  58.         $('#loading-img').show(); //hide submit button  
  59.         $("#output").html("");    
  60.     }  
  61.     else  
  62.     {  
  63.         //Output error to older unsupported browsers that doesn't support HTML5 File API  
  64.         $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");  
  65.         return false;  
  66.     }  
  67. }  
  68.   
  69. //function to format bites bit.ly/19yoIPO  
  70. function bytesToSize(bytes) {  
  71.    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; 
  72.    if (bytes == 0) return '0 Bytes'; 
  73.    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); 
  74.    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];  
  75. }  
  76.   
  77. </script>  

 processupload.php

 

PHP Code
  1. <?php  
  2. if(isset($_POST))  
  3. {  
  4.     ############ Edit settings ##############  
  5.     $ThumbSquareSize        = 200; //Thumbnail will be 200x200  
  6.     $BigImageMaxSize        = 500; //Image Maximum height or width  
  7.     $ThumbPrefix            = "thumb_"//Normal thumb Prefix  
  8.     $DestinationDirectory   = '../upload/'//specify upload directory ends with / (slash)  
  9.     $Quality                = 90; //jpeg quality  
  10.     ##########################################  
  11.       
  12.     //check if this is an ajax request  
  13.     if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){  
  14.         die();  
  15.     }  
  16.       
  17.     // check $_FILES['ImageFile'] not empty  
  18.     if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))  
  19.     {  
  20.             die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.  
  21.     }  
  22.       
  23.     // Random number will be added after image name  
  24.     $RandomNumber   = rand(0, 9999999999);   
  25.   
  26.     $ImageName      = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name  
  27.     $ImageSize      = $_FILES['ImageFile']['size']; // get original image size  
  28.     $TempSrc        = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder  
  29.     $ImageType      = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.  
  30.   
  31.     //Let's check allowed $ImageType, we use PHP SWITCH statement here  
  32.     switch(strtolower($ImageType))  
  33.     {  
  34.         case 'image/png': 
  35.             //Create a new image from file  
  36.             $CreatedImage =  imagecreatefrompng($_FILES['ImageFile']['tmp_name']); 
  37.             break; 
  38.         case 'image/gif': 
  39.             $CreatedImage =  imagecreatefromgif($_FILES['ImageFile']['tmp_name']); 
  40.             break;           
  41.         case 'image/jpeg': 
  42.         case 'image/pjpeg': 
  43.             $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']); 
  44.             break; 
  45.         default: 
  46.             die('Unsupported File!'); //output error and exit 
  47.     } 
  48.      
  49.     //PHP getimagesize() function returns height/width from image file stored in PHP tmp folder. 
  50.     //Get first two values from image, width and height.  
  51.     //list assign svalues to $CurWidth,$CurHeight 
  52.     list($CurWidth,$CurHeight)=getimagesize($TempSrc); 
  53.      
  54.     //Get file extension from Image name, this will be added after random name 
  55.     $ImageExt = substr($ImageName, strrpos($ImageName, '.')); 
  56.     $ImageExt = str_replace('.','',$ImageExt); 
  57.      
  58.     //remove extension from filename 
  59.     $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);  
  60.      
  61.     //Construct a new name with random number and extension. 
  62.     $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt; 
  63.      
  64.     //set the Destination Image 
  65.     $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory 
  66.     $DestRandImageName          = $DestinationDirectory.$NewImageName; // Image with destination directory 
  67.      
  68.     //Resize image to Specified Size by calling resizeImage function. 
  69.     if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)) 
  70.     { 
  71.         //Create a square Thumbnail right after, this time we are using cropImage() function 
  72.         if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType)) 
  73.             { 
  74.                 echo 'Error Creating thumbnail'; 
  75.             } 
  76.         /* 
  77.         We have succesfully resized and created thumbnail image 
  78.         We can now output image to user's browser or store information in the database  
  79.         */  
  80.         echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';  
  81.         echo '<tr>';  
  82.         echo '<td align="center"><img src="../upload/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail"></td>';  
  83.         echo '</tr><tr>';  
  84.         echo '<td align="center"><img src="../upload/'.$NewImageName.'" alt="Resized Image"></td>';  
  85.         echo '</tr>';  
  86.         echo '</table>';  
  87.   
  88.         /* 
  89.         // Insert info into database table! 
  90.         mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath) 
  91.         VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')"); 
  92.         */  
  93.   
  94.     }else{  
  95.         die('Resize Error'); //output error  
  96.     }  
  97. }  
  98.   
  99.   
  100. // This function will proportionally resize image   
  101. function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)  
  102. {  
  103.     //Check Image size is not 0  
  104.     if($CurWidth <= 0 || $CurHeight <= 0)   
  105.     {  
  106.         return false;  
  107.     }  
  108.       
  109.     //Construct a proportional size of new image  
  110.     $ImageScale         = min($MaxSize/$CurWidth$MaxSize/$CurHeight);   
  111.     $NewWidth           = ceil($ImageScale*$CurWidth);  
  112.     $NewHeight          = ceil($ImageScale*$CurHeight);  
  113.     $NewCanves          = imagecreatetruecolor($NewWidth$NewHeight);  
  114.       
  115.     // Resize Image  
  116.     if(imagecopyresampled($NewCanves$SrcImage,0, 0, 0, 0, $NewWidth$NewHeight$CurWidth$CurHeight))  
  117.     {  
  118.         switch(strtolower($ImageType))  
  119.         {  
  120.             case 'image/png':  
  121.                 imagepng($NewCanves,$DestFolder);  
  122.                 break;  
  123.             case 'image/gif':  
  124.                 imagegif($NewCanves,$DestFolder);  
  125.                 break;            
  126.             case 'image/jpeg':  
  127.             case 'image/pjpeg':  
  128.                 imagejpeg($NewCanves,$DestFolder,$Quality);  
  129.                 break;  
  130.             default:  
  131.                 return false;  
  132.         }  
  133.     //Destroy image, frees memory     
  134.     if(is_resource($NewCanves)) {imagedestroy($NewCanves);}   
  135.     return true;  
  136.     }  
  137.   
  138. }  
  139.   
  140. //This function corps image to create exact square images, no matter what its original size!  
  141. function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)  
  142. {      
  143.     //Check Image size is not 0  
  144.     if($CurWidth <= 0 || $CurHeight <= 0)   
  145.     {  
  146.         return false;  
  147.     }  
  148.       
  149.     //abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9  
  150.     if($CurWidth>$CurHeight)  
  151.     {  
  152.         $y_offset = 0;  
  153.         $x_offset = ($CurWidth - $CurHeight) / 2;  
  154.         $square_size    = $CurWidth - ($x_offset * 2);  
  155.     }else{  
  156.         $x_offset = 0;  
  157.         $y_offset = ($CurHeight - $CurWidth) / 2;  
  158.         $square_size = $CurHeight - ($y_offset * 2);  
  159.     }  
  160.       
  161.     $NewCanves  = imagecreatetruecolor($iSize$iSize);   
  162.     if(imagecopyresampled($NewCanves$SrcImage,0, 0, $x_offset$y_offset$iSize$iSize$square_size$square_size))  
  163.     {  
  164.         switch(strtolower($ImageType))  
  165.         {  
  166.             case 'image/png':  
  167.                 imagepng($NewCanves,$DestFolder);  
  168.                 break;  
  169.             case 'image/gif':  
  170.                 imagegif($NewCanves,$DestFolder);  
  171.                 break;            
  172.             case 'image/jpeg':  
  173.             case 'image/pjpeg':  
  174.                 imagejpeg($NewCanves,$DestFolder,$Quality);  
  175.                 break;  
  176.             default:  
  177.                 return false;  
  178.         }  
  179.     //Destroy image, frees memory     
  180.     if(is_resource($NewCanves)) {imagedestroy($NewCanves);}   
  181.     return true;  
  182.   
  183.     }  
  184.         
  185. }  

 


原文地址:http://www.freejs.net/article_biaodan_288.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值