PHP uploads and compresses images

Source: Internet
Author: User
Tags imagejpeg learn php programming
This article mainly introduces the related information for PHP to upload and compress images, upload images and then scale the thumbnails according to the proportion, if you are interested, you can refer to the examples in this article to explain how to upload and compress PHP images and share them with you for your reference. the specific content is as follows:

Use three files

  • Connect. php: connect to the database
  • Test_upload.php: execute the SQL statement
  • Upload_img.php: upload and compress images

The code for the three files is as follows:
Connect to the database:Connect. php

<?php$db_host = '';$db_user = '';$db_psw = '';$db_name = '';$db_port = '';$sqlconn=new mysqli($db_host,$db_user,$db_psw,$db_name);$q="set names utf8;";$result=$sqlconn->query($q);if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit();}?>

Run the SQL statement test_upload.php.

<?phprequire ("connect.php");require ("upload_img.php");$real_img=$uploadfile; $small_img=$uploadfile_resize;$insert_sql = "insert into img (real_img,small_img) values (?,?)";$result = $sqlconn -> prepare($insert_sql);$result -> bind_param("ss", $real_img,$small_img);$result -> execute();?>

Upload and compress images:Upload_img.php

<? Php // Set the file storage directory $ uploaddir = "upfiles/"; // set the type of the file to be uploaded $ type = array ("jpg", "gif", "bmp ", "jpeg", "png"); // gets the file extension function fileext ($ filename) {return substr (strrchr ($ filename ,'. '), 1);} // function of generating random file name random ($ length) {$ hash = 'cr-'; $ chars = 'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz '; $ max = strlen ($ chars)-1; mt_srand (double) microtime () * 1000000); for ($ I = 0; $ I <$ le Ngth; $ I ++) {$ hash. = $ chars [mt_rand (0, $ max)];} return $ hash ;} $ a = strtolower (fileext ($ _ FILES ['filename'] ['name']); // Determine the file type if (! In_array (strtolower (fileext ($ _ FILES ['filename'] ['name']), $ type) {$ text = implode (",", $ type ); $ ret_code = 3; // file type error $ page_result = $ text; $ retArray = array ('ret _ code' => $ ret_code, 'page _ result' => $ page_result); $ retJson = json_encode ($ retArray); echo $ retJson; return ;} // Generate the target file named else {$ filename = explode (". ", $ _ FILES ['filename'] ['name']); do {$ filename [0] = random (10 ); // set the length of the random number $ name = implode (". ", $ filen Ame); // $ name1 = $ name. ". mcncc "; $ uploadfile = $ uploaddir. $ name;} while (file_exists ($ uploadfile); if (move_uploaded_file ($ _ FILES ['filename'] ['tmp _ name'], $ uploadfile )) {if (is_uploaded_file ($ _ FILES ['filename'] ['tmp _ name']) {$ ret_code = 1; // Upload failed} else {// Upload succeeded $ ret_code = 0 ;}}$ retArray = array ('ret _ code' => $ ret_code ); $ retJson = json_encode ($ retArray); echo $ retJson;} // compress the image $ uploaddir_resize = "upfiles_r Esize/"; $ uploadfile_resize = $ uploaddir_resize. $ name; // $ pic_width_max = 120; // $ pic_height_max = 90; // The above and the following annotations can be used in combination, allows the image to be compressed according to the calculated ratio $ file_type = $ _ FILES ["filename"] ['type']; function ResizeImage ($ uploadfile, $ maxwidth, $ maxheight, $ name) {// get the current image size $ width = imagesx ($ uploadfile); $ height = imagesy ($ uploadfile); $ I = 0.5; // Generate the thumbnail size if ($ width> $ maxwidth) | ($ height> $ maxheight) {/* $ widthratio = $ maxwidth/ $ Width; $ heightratio = $ maxheight/$ height; if ($ widthratio <$ heightratio) {$ ratio = $ widthratio;} else {$ ratio = $ heightratio ;} $ newwidth = $ width * $ ratio; $ newheight = $ height * $ ratio; */$ newwidth = $ width * $ I; $ newheight = $ height * $ I; if (function_exists ("imagecopyresampled") {$ uploaddir_resize = imagecreatetruecolor ($ newwidth, $ newheight); imagecopyresampled ($ uploaddir_resize, $ uploa Dfile, 0, 0, 0, 0, $ newwidth, $ newheight, $ width, $ height);} else {$ uploaddir_resize = imagecreate ($ newwidth, $ newheight ); imagecopyresized ($ uploaddir_resize, $ uploadfile, 0, 0, 0, 0, $ newwidth, $ newheight, $ width, $ height);} ImageJpeg ($ uploaddir_resize, $ name ); imageDestroy ($ uploaddir_resize);} else {ImageJpeg ($ uploadfile, $ name) ;}} if ($ _ FILES ["filename"] ['size']) {if ($ file_type = "image/p Jpeg "| $ file_type =" image/jpg "| $ file_type =" image/jpeg ") {// $ im = imagecreatefromjpeg ($ _ FILES [$ upload_input_name] ['tmp _ name']); $ im = imagecreatefromjpeg ($ uploadfile );} elseif ($ file_type = "image/x-png") {// $ im = imagecreatefrompng ($ _ FILES [$ upload_input_name] ['tmp _ name']); $ im = imagecreatefromjpeg ($ uploadfile);} elseif ($ file_type = "image/gif") {// $ im = imagecreatefromgif ($ _ FILES [$ uplo Ad_input_name] ['tmp _ name']); $ im = imagecreatefromjpeg ($ uploadfile);} else // Default jpg {$ im = imagecreatefromjpeg ($ uploadfile );} if ($ im) {ResizeImage ($ im, $ pic_width_max, $ pic_height_max, $ uploadfile_resize); ImageDestroy ($ im) ;}}?>

Change the information in connect. php and test_upload.php according to the actual situation.

The above is the PHP method for uploading and compressing images. I hope it will be helpful for you to learn php programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.