Ajax 上传图片并可以生成指定大小缩略图
XML/HTML Code
- <div id="upload-wrapper">
- <div align="center">
- <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
- <input name="ImageFile" id="imageInput" type="file" />
- <input type="submit" id="submit-btn" value="Upload" />
- <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
- </form>
- <div id="output"></div>
- </div>
- </div>
JavaScript Code
- <script type="text/javascript">
- $(document).ready(function() {
- var options = {
- target: '#output', // target element(s) to be updated with server response
- beforeSubmit: beforeSubmit, // pre-submit callback
- success: afterSuccess, // post-submit callback
- resetForm: true // reset the form after successful submit
- };
- $('#MyUploadForm').submit(function() {
- $(this).ajaxSubmit(options);
- // always return false to prevent standard browser submit and page navigation
- return false;
- });
- });
- function afterSuccess()
- {
- $('#submit-btn').show(); //hide submit button
- $('#loading-img').hide(); //hide submit button
- }
- //function to check file size before uploading.
- function beforeSubmit(){
- //check whether browser fully supports all File API
- if (window.File && window.FileReader && window.FileList && window.Blob)
- {
- if( !$('#imageInput').val()) //check empty input filed
- {
- $("#output").html("Are you kidding me?");
- return false
- }
- var fsize = $('#imageInput')[0].files[0].size; //get file size
- var ftype = $('#imageInput')[0].files[0].type; // get file type
- //allow only valid image file types
- switch(ftype)
- {
- case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
- break;
- default:
- $("#output").html("<b>"+ftype+"</b> Unsupported file type!");
- return false
- }
- //Allowed file size is less than 1 MB (1048576)
- if(fsize>1048576)
- {
- $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");
- return false
- }
- $('#submit-btn').hide(); //hide submit button
- $('#loading-img').show(); //hide submit button
- $("#output").html("");
- }
- else
- {
- //Output error to older unsupported browsers that doesn't support HTML5 File API
- $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
- return false;
- }
- }
- //function to format bites bit.ly/19yoIPO
- function bytesToSize(bytes) {
- var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
- if (bytes == 0) return '0 Bytes';
- var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
- return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
- }
- </script>
processupload.php
PHP Code
- <?php
- if(isset($_POST))
- {
- ############ Edit settings ##############
- $ThumbSquareSize = 200; //Thumbnail will be 200x200
- $BigImageMaxSize = 500; //Image Maximum height or width
- $ThumbPrefix = "thumb_"; //Normal thumb Prefix
- $DestinationDirectory = '../upload/'; //specify upload directory ends with / (slash)
- $Quality = 90; //jpeg quality
- ##########################################
- //check if this is an ajax request
- if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
- die();
- }
- // check $_FILES['ImageFile'] not empty
- if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
- {
- die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.
- }
- // Random number will be added after image name
- $RandomNumber = rand(0, 9999999999);
- $ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name
- $ImageSize = $_FILES['ImageFile']['size']; // get original image size
- $TempSrc = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder
- $ImageType = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
- //Let's check allowed $ImageType, we use PHP SWITCH statement here
- switch(strtolower($ImageType))
- {
- case 'image/png':
- //Create a new image from file
- $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!'); //output error and exit
- }
- //PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
- //Get first two values from image, width and height.
- //list assign svalues to $CurWidth,$CurHeight
- list($CurWidth,$CurHeight)=getimagesize($TempSrc);
- //Get file extension from Image name, this will be added after random name
- $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
- $ImageExt = str_replace('.','',$ImageExt);
- //remove extension from filename
- $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
- //Construct a new name with random number and extension.
- $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
- //set the Destination Image
- $thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
- $DestRandImageName = $DestinationDirectory.$NewImageName; // Image with destination directory
- //Resize image to Specified Size by calling resizeImage function.
- if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
- {
- //Create a square Thumbnail right after, this time we are using cropImage() function
- if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
- {
- echo 'Error Creating thumbnail';
- }
- /*
- We have succesfully resized and created thumbnail image
- We can now output image to user's browser or store information in the database
- */
- echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
- echo '<tr>';
- echo '<td align="center"><img src="../upload/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail"></td>';
- echo '</tr><tr>';
- echo '<td align="center"><img src="../upload/'.$NewImageName.'" alt="Resized Image"></td>';
- echo '</tr>';
- echo '</table>';
- /*
- // Insert info into database table!
- mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
- VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
- */
- }else{
- die('Resize Error'); //output error
- }
- }
- // This function will proportionally resize image
- function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
- {
- //Check Image size is not 0
- if($CurWidth <= 0 || $CurHeight <= 0)
- {
- return false;
- }
- //Construct a proportional size of new image
- $ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
- $NewWidth = ceil($ImageScale*$CurWidth);
- $NewHeight = ceil($ImageScale*$CurHeight);
- $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
- // Resize Image
- 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;
- }
- //Destroy image, frees memory
- if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
- return true;
- }
- }
- //This function corps image to create exact square images, no matter what its original size!
- function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
- {
- //Check Image size is not 0
- if($CurWidth <= 0 || $CurHeight <= 0)
- {
- return false;
- }
- //abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9
- 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;
- }
- //Destroy image, frees memory
- if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
- return true;
- }
- }
相关推荐
功能:可自动将原始图片(未经裁剪的原始图片)自动生成一个规定大小的缩略图和大图片存放至指定目录,并可自动将图片记录添加到数据库。 方法:在网站根目录下新建一个目录(目录名为英文名),将原始图片拷贝进去...
支持10M以上的大图片上传,自动生成缩略图,加快显示速度 批量上传图片,一键上传文件夹内所有选择的图片 图片自动按年月生成文件夹保存,让图片管理更有条理 缩略图后台可以设置尺寸,系统智能识别,生成小...
支持10M以上的大图片上传,自动生成缩略图,加快显示速度 批量上传图片,一键上传文件夹内所有选择的图片 图片自动按年月生成文件夹保存,让图片管理更有条理 缩略图后台可以设置尺寸,系统智能识别,...
3.简化图片添加过程,直接上传图片到图片目录即可,相册自动获取、遍历新上传的图片,并生成缩略图 4.增加多页跳转功能 5.简单易用,直接插入控件到你的页面,并进行相关设置即可使用 PhotoAlbum 控件说明: 1.该...
上传完毕自动生成等比例缩略图。 52.可以同时下载多张网络图片到空间,并可设置水印等功能。 53.上传时可自由设置是否在照片上添加文字水印、图片水印或不添加水印。 54.用户分组设置,可分多组域名及多台服务器协同...
支持10M以上的大图片上传,自动生成缩略图,加快显示速度 批量上传图片,一键上传文件夹内所有选择的图片 图片自动按年月生成文件夹保存,让图片管理更有条理 缩略图后台可以设置尺寸,系统智能识别,生成小...
【增加】单图片简洁模式也可以查看缩略图;【增加】随机数字段,在指定范围内随机生成;【增加】多模型数据调用,可以在一个列表中调用多个模型的数据;【增加】单图片多小图时,截取小图的方式由之前的等比例缩小后...
【增加】单图片简洁模式也可以查看缩略图;【增加】随机数字段,在指定范围内随机生成;【增加】多模型数据调用,可以在一个列表中调用多个模型的数据;【增加】单图片多小图时,截取小图的方式由之前的等比例缩小后...
【增加】单图片简洁模式也可以查看缩略图; 【增加】随机数字段,在指定范围内随机生成; 【增加】多模型数据调用,可以在一个列表中调用多个模型的数据; 【增加】单图片多小图时,截取小图的方式由之前的等比例...
上传完毕自动生成等比例缩略图。 52.可以同时下载多张网络图片到空间,并可设置水印等功能。 53.上传时可自由设置是否在照片上添加文字水印、图片水印或不添加水印。 54.用户分组设置,可分多组域名及多台服务器协同...
2、水印缩略强化,支持按栏目按字段指定缩略图大小设置。3、调整程序目录接口,开放修改后台入口及文件名。4、加入表单调用标签,可以在任意位置调用表单发布form5、自定义频道功能,可以自由增加自定义频道,独立...
4)修正GIf图像生成缩略图质量较低的BUG! 2008/10/20 Version 5.0.7 For VS2005/2008 Updates: 1)修正每次新建文件夹默认目录名相同导致的问题,现在新建文件夹的默认目录名以newFolder年-月-日-时分秒来命名,杜绝...
可设置是否自动获取文章内的图片做为文章的缩略图. 14.通过AJAX实现无刷新评论功能.即评论文章不会刷新整个网页. 15.后台支持往文章系统批量发表图片或发表组图功能 16.支持续页发表功能,比如一篇文章太长,可以分多...
2、水印缩略强化,支持按栏目按字段指定缩略图大小设置。 3、调整程序目录接口,开放修改后台入口及文件名。 4、加入表单调用标签,可以在任意位置调用表单发布form 5、自定义频道功能,可以自由增加自定义频道,...
10.18 为列表添加自定义的缩略图图标 10.19 创建列表日历的效果 10.20 动态创建listview列表项 10.21 动态加载和切换页面 10.22 在页面切换时显示加载进度框 10.23 在屏幕旋转时更改显示样式 10.24 在列表框中实现...
【增加】单图片简洁模式也可以查看缩略图 【增加】随机数字段,在指定范围内随机生成 【增加】多模型数据调用,可以在一个列表中调用多个模型的数据。 【增加】单图片多小图时,截取小图的方式由之前的等比例缩小...
15.28 等比例缩略图 15.29 用JavaScript导出图像到Excel 15.30 使用VML打造可改变大小的圆框 15.31 JavaScript实现文档结构图 15.32 判断一副图片是否加载完毕 第16章 页面数据的验证 16.1 验证字符串是否全由数字...
【增加】单图片简洁模式也可以查看缩略图 【增加】随机数字段,在指定范围内随机生成 【增加】多模型数据调用,可以在一个列表中调用多个模型的数据。 【增加】单图片多小图时,截取小图的方式由之前的等比例缩小...
4)修正GIf图像生成缩略图质量较低的BUG! 2008/10/20 Version 5.0.7 For VS2005/2008 Updates: 1)修正每次新建文件夹默认目录名相同导致的问题,现在新建文件夹的默认目录名以newFolder年-月-日-时分秒来...