<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>upload image - itOffside.com | บทความการเขียนโปรแกรม เรื่องราวข้อมูลเทคโนโลยี</title>
	<atom:link href="https://www.itoffside.com/tag/upload-image/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.itoffside.com</link>
	<description>ข้อมูลข่าวสารและเรื่องราวบนโลกของไอทีที่ ล้ำหน้า พร้อมสาระการเขียนโปรแกรมคอมพิวเตอร์</description>
	<lastBuildDate>Mon, 02 Feb 2015 15:32:49 +0000</lastBuildDate>
	<language>th</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.5</generator>

<image>
	<url>https://www.itoffside.com/wp-content/uploads/2020/04/cropped-favicon-96x96-1-32x32.png</url>
	<title>upload image - itOffside.com | บทความการเขียนโปรแกรม เรื่องราวข้อมูลเทคโนโลยี</title>
	<link>https://www.itoffside.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>การอัพโหลดรูปภาพและ resize แบบ AJAX โดยใช้ PHP และ jQuery</title>
		<link>https://www.itoffside.com/ajax-image-upload-and-resize-with-php-jquery/</link>
					<comments>https://www.itoffside.com/ajax-image-upload-and-resize-with-php-jquery/#comments</comments>
		
		<dc:creator><![CDATA[Onmobile]]></dc:creator>
		<pubDate>Mon, 02 Feb 2015 15:32:49 +0000</pubDate>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php5]]></category>
		<category><![CDATA[upload image]]></category>
		<guid isPermaLink="false">https://www.itoffside.com/?p=2451</guid>

					<description><![CDATA[<p>ปัจจุบันการอัพโหลดไฟล์รูปภาพและ resize ขนาดรูปภาพ มี code ดาวน์โหลดให้เลือกใช้งานมากมายแต่บทความในบทความนี้ผมแนะนำการอัพโหลดไฟล์รูปภาพแบบ AJAX โดยใช้ PHP และ ใช้ jQuery เป็นเครื่องมือในการอัพโหลดรูปภาพซึ่งการอัพโหลดรูปภาพแบบ AJAX นั้นมีจุดเด่นคือไม่ต้อง Refresh หน้าเว็บเพจจึงทำให้การอัพโหลดมีความรวด...</p>
<p>The post <a href="https://www.itoffside.com/ajax-image-upload-and-resize-with-php-jquery/">การอัพโหลดรูปภาพและ resize แบบ AJAX โดยใช้ PHP และ jQuery</a> first appeared on <a href="https://www.itoffside.com">itOffside.com | บทความการเขียนโปรแกรม เรื่องราวข้อมูลเทคโนโลยี</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>ปัจจุบันการอัพโหลดไฟล์รูปภาพและ resize ขนาดรูปภาพ มี code ดาวน์โหลดให้เลือกใช้งานมากมายแต่บทความในบทความนี้ผมแนะนำการอัพโหลดไฟล์รูปภาพแบบ <strong><span style="text-decoration: underline;">AJAX</span> </strong>โดยใช้ <span style="text-decoration: underline;"><strong>PHP</strong> </span>และ ใช้ <span style="text-decoration: underline;"><strong>jQuery</strong> </span>เป็นเครื่องมือในการอัพโหลดรูปภาพซึ่งการอัพโหลดรูปภาพแบบ AJAX นั้นมีจุดเด่นคือไม่ต้อง Refresh หน้าเว็บเพจจึงทำให้การอัพโหลดมีความรวดเร็วและใช้ Data Transfer น้อยลง โดยผมจะใช้เทคนิค <a href="http://www.w3.org/TR/file-upload/" target="_blank">HTML5 File API</a> ในการตรวจสอบขนาดไฟล์และประเภทของไฟล์ก่อนที่จะอัพโหลดจากนั้นผมจะสร้างไฟล์รูปภาพ 2 ไฟล์ คือไฟล์รูปภาพ Original และ รูปภาพแบบปรับขนาดแล้ว สำหรับบทความนี้เน้นการใช้งานพื้นฐานและง่ายต่อการเรียนรู้และเข้าใจ<span id="more-2451"></span></p>
<p>รูปภาพโครงสร้างโฟล์เดอร์และไฟล์ ในบทความนี้ ผมสร้างโปรเจ็คชื่อว่า ajaxuploadimg จะเห็นได้ว่าไฟล์ที่จำเป็นต้องใช้งานมีดังนี้<br />
1. ไฟล์ index.php ทำหน้าที่แสดงหน้าจออัพโหลดและส่งข้อมูลอัพโหลดผ่าน AJAX<br />
2. ไฟล์ processupload.php ทำหน้าอัพโหลดรูปภาพโดยใช้ภาษา PHP คุณสามารถตั้งค่าการอัพโหลดได้ที่ไฟล์นี้ เช่นกำหนดขนาดรูปภาพ กำหนดพาธที่เก็บรูปภาพ<br />
3. โฟล์เดอร์ uploads ทำหน้าที่เก็บรูปภาพที่อัพโหลด<br />
4. โฟล์เดอร์ js/images/style เก็บไฟล์ที่จำเป็นต้องเรียกใช้งานเช่น jquery.form เป็นต้น</p>
<p>โดยไฟล์เหล่านี้สามารถดาวน์โหลดได้ที่ด้านล่างบทความ<br />
<img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-2453" src="https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-01.jpg" alt="ajaxuploadimage-01" width="537" height="336" srcset="https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-01.jpg 537w, https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-01-300x188.jpg 300w" sizes="(max-width: 537px) 100vw, 537px" /></p>
<p>1. สร้างฟอร์ม Upload รูปภาพ ให้คุณสร้างไฟล์ index.php ขึ้นมาแล้วนำ Code นี้ไปใส่ภายใน Tag &lt;Body&gt;</p><pre class="crayon-plain-tag">&lt;form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"&gt;
 &lt;input name="image_file" id="imageInput" type="file" /&gt;
 &lt;input type="submit" id="submit-btn" value="Upload" /&gt;
 &lt;img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/&gt;
 &lt;/form&gt;
 &lt;div id="output"&gt;&lt;/div&gt;</pre><p><strong><em>ผลลัพธ์</em></strong><br />
<img decoding="async" class="alignnone  wp-image-2454" src="https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-02.jpg" alt="ajaxuploadimage-02" width="510" height="266" srcset="https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-02.jpg 621w, https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-02-300x157.jpg 300w" sizes="(max-width: 510px) 100vw, 510px" /></p>
<p>2. ในบทความนี้มีการเรียกใช้งาน jQuery เพื่อให้การสร้าง code ง่ายขึ้นโดยปลักอิน jQuery ทำหน้าที่ในการสร้าง<em> AJAX upload</em> เมื่อมีการคลิกปุ่ม Upload (พร้อมกับการตรวจสอบไฟล์รูปภาพ)<br />
ให้คุณนำ code นี้ไปใส่ในส่วนของ &lt;head&gt; ในไฟล์ index.php</p><pre class="crayon-plain-tag">&lt;script type="text/javascript" src="js/jquery-1.10.2.min.js"&gt;&lt;/script&gt;
 &lt;script type="text/javascript" src="js/jquery.form.min.js"&gt;&lt;/script&gt;

 &lt;script type="text/javascript"&gt;
 $(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 &amp;&amp; window.FileReader &amp;&amp; window.FileList &amp;&amp; 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("&lt;b&gt;" + ftype + "&lt;/b&gt; Unsupported file type!");
 return false
 }

 //Allowed file size is less than 1 MB (1048576)
 if (fsize &gt; 1048576)
 {
 $("#output").html("&lt;b&gt;" + bytesToSize(fsize) + "&lt;/b&gt; Too big Image file! &lt;br /&gt;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 browsers that do not 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];
 }

 &lt;/script&gt;
 &lt;link href="style/style.css" rel="stylesheet" type="text/css"&gt;</pre><p>และไฟล์ index.php มี code เป็นดังนี้</p><pre class="crayon-plain-tag">&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
 &lt;head&gt;
 &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
 &lt;title&gt;Ajax Upload and Resize with jQuery and PHP - Demo&lt;/title&gt;
 &lt;script type="text/javascript" src="js/jquery-1.10.2.min.js"&gt;&lt;/script&gt;
 &lt;script type="text/javascript" src="js/jquery.form.min.js"&gt;&lt;/script&gt;

 &lt;script type="text/javascript"&gt;
 $(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 &amp;&amp; window.FileReader &amp;&amp; window.FileList &amp;&amp; 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("&lt;b&gt;" + ftype + "&lt;/b&gt; Unsupported file type!");
 return false
 }

 //Allowed file size is less than 1 MB (1048576)
 if (fsize &gt; 1048576)
 {
 $("#output").html("&lt;b&gt;" + bytesToSize(fsize) + "&lt;/b&gt; Too big Image file! &lt;br /&gt;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 browsers that do not 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];
 }

 &lt;/script&gt;
 &lt;link href="style/style.css" rel="stylesheet" type="text/css"&gt;
 &lt;/head&gt;
 &lt;body&gt;
 &lt;div id="upload-wrapper"&gt;
 &lt;div align="center"&gt;
 &lt;h3&gt;Ajax Image Uploader&lt;/h3&gt;
 &lt;form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"&gt;
 &lt;input name="image_file" id="imageInput" type="file" /&gt;
 &lt;input type="submit" id="submit-btn" value="Upload" /&gt;
 &lt;img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/&gt;
 &lt;/form&gt;
 &lt;div id="output"&gt;&lt;/div&gt;
 &lt;/div&gt;
 &lt;/div&gt;

 &lt;/body&gt;
&lt;/html&gt;</pre><p>3. ทำการสร้างไฟล์ processupload.php แล้วนำ code ไปใส่<br />
อธิบายสำหรับไฟล์นี้ ใช้สำหรับตั้งค่าต่างๆเช่น กำหนดที่อยู่ในการอัพโหลดหรือ ขนาดไฟล์ที่จะอัพโหลด เป็นต้นโดยคุณสามารถกำหนดการตั้งค่าได้ที่ไฟล์นี้</p><pre class="crayon-plain-tag">&lt;?php

############ Configuration ##############
$thumb_square_size = 200; //Thumbnails will be cropped to 200x200 pixels
$max_image_size = 500; //Maximum image size (height and width)
$thumb_prefix = "thumb_"; //Normal thumb Prefix
$destination_folder = $_SERVER['DOCUMENT_ROOT'] . "/ajaxuploadimg/uploads/"; //upload directory ends with / (slash)
$jpeg_quality = 90; //jpeg quality
##########################################
//continue only if $_POST is set and it is a Ajax request
if (isset($_POST) &amp;&amp; isset($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

 // check $_FILES['ImageFile'] not empty
 if (!isset($_FILES['image_file']) || !is_uploaded_file($_FILES['image_file']['tmp_name'])) {
 die('Image file is Missing!'); // output error when above checks fail.
 }

 //uploaded file info we need to proceed
 $image_name = $_FILES['image_file']['name']; //file name
 $image_size = $_FILES['image_file']['size']; //file size
 $image_temp = $_FILES['image_file']['tmp_name']; //file temp

 $image_size_info = getimagesize($image_temp); //get image size

 if ($image_size_info) {
 $image_width = $image_size_info[0]; //image width
 $image_height = $image_size_info[1]; //image height
 $image_type = $image_size_info['mime']; //image type
 } else {
 die("Make sure image file is valid!");
 }

 //switch statement below checks allowed image type 
 //as well as creates new image from given file 
 switch ($image_type) {
 case 'image/png':
 $image_res = imagecreatefrompng($image_temp);
 break;
 case 'image/gif':
 $image_res = imagecreatefromgif($image_temp);
 break;
 case 'image/jpeg': case 'image/pjpeg':
 $image_res = imagecreatefromjpeg($image_temp);
 break;
 default:
 $image_res = false;
 }

 if ($image_res) {
 //Get file extension and name to construct new file name 
 $image_info = pathinfo($image_name);
 $image_extension = strtolower($image_info["extension"]); //image extension
 $image_name_only = strtolower($image_info["filename"]); //file name only, no extension
 //create a random name for new image (Eg: fileName_293749.jpg) ;
 $new_file_name = $image_name_only . '_' . rand(0, 9999999999) . '.' . $image_extension;

 //folder path to save resized images and thumbnails
 $thumb_save_folder = $destination_folder . $thumb_prefix . $new_file_name;
 $image_save_folder = $destination_folder . $new_file_name;

 //call normal_resize_image() function to proportionally resize image
 if (normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality)) {
 //call crop_image_square() function to create square thumbnails
 if (!crop_image_square($image_res, $thumb_save_folder, $image_type, $thumb_square_size, $image_width, $image_height, $jpeg_quality)) {
 die('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 '&lt;div align="center"&gt;';
 echo '&lt;img src="uploads/' . $thumb_prefix . $new_file_name . '" alt="Thumbnail"&gt;';
 echo '&lt;br /&gt;';
 echo '&lt;img src="uploads/' . $new_file_name . '" alt="Resized Image"&gt;';
 echo '&lt;/div&gt;';
 }

 imagedestroy($image_res); //freeup memory
 }
}

##### This function will proportionally resize image ##### 

function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality) {

 if ($image_width &lt;= 0 || $image_height &lt;= 0) {
 return false;
 } //return false if nothing to resize
 //do not resize if image is smaller than max size
 if ($image_width &lt;= $max_size &amp;&amp; $image_height &lt;= $max_size) {
 if (save_image($source, $destination, $image_type, $quality)) {
 return true;
 }
 }

 //Construct a proportional size of new image
 $image_scale = min($max_size / $image_width, $max_size / $image_height);
 $new_width = ceil($image_scale * $image_width);
 $new_height = ceil($image_scale * $image_height);

 $new_canvas = imagecreatetruecolor($new_width, $new_height); //Create a new true color image
 //Copy and resize part of an image with resampling
 if (imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)) {
 save_image($new_canvas, $destination, $image_type, $quality); //save resized image
 }

 return true;
}

##### This function corps image to create exact square, no matter what its original size! ######

function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality) {
 if ($image_width &lt;= 0 || $image_height &lt;= 0) {
 return false;
 } //return false if nothing to resize

 if ($image_width &gt; $image_height) {
 $y_offset = 0;
 $x_offset = ($image_width - $image_height) / 2;
 $s_size = $image_width - ($x_offset * 2);
 } else {
 $x_offset = 0;
 $y_offset = ($image_height - $image_width) / 2;
 $s_size = $image_height - ($y_offset * 2);
 }
 $new_canvas = imagecreatetruecolor($square_size, $square_size); //Create a new true color image
 //Copy and resize part of an image with resampling
 if (imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)) {
 save_image($new_canvas, $destination, $image_type, $quality);
 }

 return true;
}

##### Saves image resource to file ##### 

function save_image($source, $destination, $image_type, $quality) {
 switch (strtolower($image_type)) {//determine mime type
 case 'image/png':
 imagepng($source, $destination);
 return true; //save png file
 break;
 case 'image/gif':
 imagegif($source, $destination);
 return true; //save gif file
 break;
 case 'image/jpeg': case 'image/pjpeg':
 imagejpeg($source, $destination, $quality);
 return true; //save jpeg file
 break;
 default: return false;
 }
}</pre><p><em><strong>ผลลัพธ์</strong></em><br />
<img decoding="async" class="alignnone size-full wp-image-2455" src="https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-03.jpg" alt="ajaxuploadimage-03" width="618" height="530" srcset="https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-03.jpg 618w, https://www.itoffside.com/wp-content/uploads/2015/02/ajaxuploadimage-03-300x257.jpg 300w" sizes="(max-width: 618px) 100vw, 618px" /></p>
<p>สำหรับลิงค์ดาวน์โหลดไฟล์ทั้งหมด สามารถดาวน์โหลดได้ที่นี้ <a title="การอัพโหลดรูปภาพด้วย PHP AJAX" href="http://www.mediafire.com/download/shlmsblbcxya7b4/ajaxuploadimg.rar" target="_blank">คลิกที่นี้เพื่อดาวน์โหลด</a></p>
<p>สำหรับบทความนี้ก็จบแล้วสำหรับเรื่อง การอัพโหลดโดยใช้ PHP และ AJAX และขอบคุณสำหรับผู้พัฒนา Code ที่เว็บ <a href="http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php" target="_blank">http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php</a></p>
<p>หากใครมีข้อสงสัยหรือคำถามสามารถเขียนคำถามไว้ใน Comment ได้เลยครับ</p><p>The post <a href="https://www.itoffside.com/ajax-image-upload-and-resize-with-php-jquery/">การอัพโหลดรูปภาพและ resize แบบ AJAX โดยใช้ PHP และ jQuery</a> first appeared on <a href="https://www.itoffside.com">itOffside.com | บทความการเขียนโปรแกรม เรื่องราวข้อมูลเทคโนโลยี</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.itoffside.com/ajax-image-upload-and-resize-with-php-jquery/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
	</channel>
</rss>
