`

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

0
0
分享到:
评论

相关推荐

    ASP+Ajax+ASPJepg图片批量导入并生成大小图程序

    功能:可自动将原始图片(未经裁剪的原始图片)自动生成一个规定大小的缩略图和大图片存放至指定目录,并可自动将图片记录添加到数据库。 方法:在网站根目录下新建一个目录(目录名为英文名),将原始图片拷贝进去...

    嵩嵩图片管理系统V8.0

    支持10M以上的大图片上传,自动生成缩略图,加快显示速度 批量上传图片,一键上传文件夹内所有选择的图片 图片自动按年月生成文件夹保存,让图片管理更有条理 缩略图后台可以设置尺寸,系统智能识别,生成小...

    嵩嵩图片(相册)管理系统 v8.0.rar

    支持10M以上的大图片上传,自动生成缩略图,加快显示速度 批量上传图片,一键上传文件夹内所有选择的图片 图片自动按年月生成文件夹保存,让图片管理更有条理 缩略图后台可以设置尺寸,系统智能识别,...

    ASP.NET相册控件(含源码)

    3.简化图片添加过程,直接上传图片到图片目录即可,相册自动获取、遍历新上传的图片,并生成缩略图 4.增加多页跳转功能 5.简单易用,直接插入控件到你的页面,并进行相关设置即可使用 PhotoAlbum 控件说明: 1.该...

    图片管理系统(桃源相册管理)

    上传完毕自动生成等比例缩略图。 52.可以同时下载多张网络图片到空间,并可设置水印等功能。 53.上传时可自由设置是否在照片上添加文字水印、图片水印或不添加水印。 54.用户分组设置,可分多组域名及多台服务器协同...

    嵩嵩图片管理系统源码 v8.0

    支持10M以上的大图片上传,自动生成缩略图,加快显示速度 批量上传图片,一键上传文件夹内所有选择的图片 图片自动按年月生成文件夹保存,让图片管理更有条理 缩略图后台可以设置尺寸,系统智能识别,生成小...

    易点内容管理系统(DianCMS) 6.4.0 SQL.rar

    【增加】单图片简洁模式也可以查看缩略图;【增加】随机数字段,在指定范围内随机生成;【增加】多模型数据调用,可以在一个列表中调用多个模型的数据;【增加】单图片多小图时,截取小图的方式由之前的等比例缩小后...

    易点内容管理系统(DianCMS) 6.4.0 Access.rar

    【增加】单图片简洁模式也可以查看缩略图;【增加】随机数字段,在指定范围内随机生成;【增加】多模型数据调用,可以在一个列表中调用多个模型的数据;【增加】单图片多小图时,截取小图的方式由之前的等比例缩小后...

    DianCMS.SQL_6.4.0.7z

    【增加】单图片简洁模式也可以查看缩略图; 【增加】随机数字段,在指定范围内随机生成; 【增加】多模型数据调用,可以在一个列表中调用多个模型的数据; 【增加】单图片多小图时,截取小图的方式由之前的等比例...

    桃源相册管理系统v2.3

    上传完毕自动生成等比例缩略图。 52.可以同时下载多张网络图片到空间,并可设置水印等功能。 53.上传时可自由设置是否在照片上添加文字水印、图片水印或不添加水印。 54.用户分组设置,可分多组域名及多台服务器协同...

    DOYO通用建站系统 2.3.rar

    2、水印缩略强化,支持按栏目按字段指定缩略图大小设置。3、调整程序目录接口,开放修改后台入口及文件名。4、加入表单调用标签,可以在任意位置调用表单发布form5、自定义频道功能,可以自由增加自定义频道,独立...

    商用版本文本编辑器DotNetTextBoxV6.0.8Source 源码

    4)修正GIf图像生成缩略图质量较低的BUG! 2008/10/20 Version 5.0.7 For VS2005/2008 Updates: 1)修正每次新建文件夹默认目录名相同导致的问题,现在新建文件夹的默认目录名以newFolder年-月-日-时分秒来命名,杜绝...

    PHP168建站系统

    可设置是否自动获取文章内的图片做为文章的缩略图. 14.通过AJAX实现无刷新评论功能.即评论文章不会刷新整个网页. 15.后台支持往文章系统批量发表图片或发表组图功能 16.支持续页发表功能,比如一篇文章太长,可以分多...

    DOYO通用建站系统 v2.3 build20140425.zip

    2、水印缩略强化,支持按栏目按字段指定缩略图大小设置。 3、调整程序目录接口,开放修改后台入口及文件名。 4、加入表单调用标签,可以在任意位置调用表单发布form 5、自定义频道功能,可以自由增加自定义频道,...

    超实用的jQuery代码段

    10.18 为列表添加自定义的缩略图图标 10.19 创建列表日历的效果 10.20 动态创建listview列表项 10.21 动态加载和切换页面 10.22 在页面切换时显示加载进度框 10.23 在屏幕旋转时更改显示样式 10.24 在列表框中实现...

    易点内容管理系统 DianCMS v6.4.0 ACC版.zip

    【增加】单图片简洁模式也可以查看缩略图 【增加】随机数字段,在指定范围内随机生成 【增加】多模型数据调用,可以在一个列表中调用多个模型的数据。 【增加】单图片多小图时,截取小图的方式由之前的等比例缩小...

    《程序天下:JavaScript实例自学手册》光盘源码

    15.28 等比例缩略图 15.29 用JavaScript导出图像到Excel 15.30 使用VML打造可改变大小的圆框 15.31 JavaScript实现文档结构图 15.32 判断一副图片是否加载完毕 第16章 页面数据的验证 16.1 验证字符串是否全由数字...

    易点内容管理系统 DianCMS v6.4.0 SQL版.zip

    【增加】单图片简洁模式也可以查看缩略图 【增加】随机数字段,在指定范围内随机生成 【增加】多模型数据调用,可以在一个列表中调用多个模型的数据。 【增加】单图片多小图时,截取小图的方式由之前的等比例缩小...

    DotNetTextBox V6.0.10 商业版 下载 (已知最新)

    4)修正GIf图像生成缩略图质量较低的BUG! 2008/10/20 Version 5.0.7 For VS2005/2008 Updates: 1)修正每次新建文件夹默认目录名相同导致的问题,现在新建文件夹的默认目录名以newFolder年-月-日-时分秒来...

Global site tag (gtag.js) - Google Analytics