本文实例讲解了PHP图片上传并压缩的实现方法,分享给大家供大家参考,具体内容如下

使用到三个文件

  • connect.php:连接数据库
  • test_upload.php:执行SQL语句
  • upload_img.php:上传图片并压缩

三个文件代码如下:
连接数据库: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();
}
?>
执行SQL语句:test_upload.php <?php
require ("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_img.php
? <?php
//设置文件保存目录
$uploaddir = "upfiles/";
//设置允许上传文件的类型
$type=array("jpg","gif","bmp","jpeg","png"); //获取文件后缀名函数
function fileext($filename)
{
return substr(strrchr($filename, '.'), 1);
} //生成随机文件名函数
function random($length)
{
$hash = 'CR-';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
$max = strlen($chars) - 1;
mt_srand((double)microtime() * 1000000);
for($i = 0; $i < $length; $i++)
{
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
} $a=strtolower(fileext($_FILES['filename']['name'])); //判断文件类型
if(!in_array(strtolower(fileext($_FILES['filename']['name'])),$type))
{
$text=implode(",",$type);
$ret_code=3;//文件类型错误
$page_result=$text;
$retArray = array('ret_code' => $ret_code,'page_result'=>$page_result);
$retJson = json_encode($retArray);
echo $retJson;
return;
} //生成目标文件的文件名
else
{
$filename=explode(".",$_FILES['filename']['name']);
do
{
$filename[0]=random(10); //设置随机数长度
$name=implode(".",$filename);
//$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;//上传失败
}
else
{//上传成功
$ret_code=0;
}
}
$retArray = array('ret_code' => $ret_code);
$retJson = json_encode($retArray);
echo $retJson;
} //压缩图片 $uploaddir_resize="upfiles_resize/";
$uploadfile_resize=$uploaddir_resize.$name; //$pic_width_max=120;
//$pic_height_max=90;
//以上与下面段注释可以联合使用,可以使图片根据计算出来的比例压缩 $file_type=$_FILES["filename"]['type']; function ResizeImage($uploadfile,$maxwidth,$maxheight,$name)
{
//取得当前图片大小
$width = imagesx($uploadfile);
$height = imagesy($uploadfile);
$i=0.5;
//生成缩略图的大小
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, $uploadfile, 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/pjpeg"||$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[$upload_input_name]['tmp_name']);
$im = imagecreatefromjpeg($uploadfile);
}
else//默认jpg
{
$im = imagecreatefromjpeg($uploadfile);
}
if($im)
{
ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize); ImageDestroy ($im);
}
}
?>

  请按照现实情况更改connect.php,test_upload.php中对应的信息。

转自:http://www.jb51.net/article/76763.htm

PHP实现图片上传并压缩的更多相关文章

  1. vuejs开发组件分享之H5图片上传、压缩及拍照旋转的问题处理

    一.前言 三年.net开发转前端已经四个月了,前端主要用webpack+vue,由于后端转过来的,前端不够系统,希望分享下开发心得与园友一起学习. 图片的上传之前都是用的插件(ajaxupload), ...

  2. html + js 实现图片上传,压缩,预览及图片压缩后得到Blob对象继续上传问题

    先上效果 上传图片后(设置了最多上传3张图片,三张后上传按钮消失) 点击图片放大,可以使用删除和旋转按钮 (旋转功能主要是因为ios手机拍照后上传会有写图片被自动旋转,通过旋转功能可以调正) html ...

  3. 图片上传前 压缩,base64图片压缩 Exif.js处理ios拍照倒置等问题

    曾写过在前端把图片按比例压缩不失真上传服务器的前端和后台,可惜没有及时做总结保留代码,只记得js利用了base64位压缩和Exif.js进行图片处理,还有其中让我头疼的ios拍照上传后会倒置等诸多问题 ...

  4. H5图片上传、压缩

    1.注册input file标签的onchange事件: 2.检查图片格式: 3.检查图片大小: 4.压缩图片 5.上传图片至服务器: 前端代码: document.getElementById('i ...

  5. vue下实现input实现图片上传,压缩,拼接以及旋转

    背景 作为一名前端工作人员,相信大家在开发系统的时候,经常有遇到需要这么一种需求,就是需要为用户保存上传的图片,很多小白遇到这个问题的时候,都会虎躯一震,以为会是一个棘手的问题,当你读完这篇文章的时候 ...

  6. iOS图片上传及压缩

    提到从摄像头/相册获取图片是面向终端用户的,由用户去浏览并选择图片为程序使用.在这里,我们需要过UIImagePickerController类来和用户交互. 使用UIImagePickerContr ...

  7. php图片上传旋转压缩方法

    用到php的exif扩展,需要开启exif 在php.ini文件中去掉exif组件的注释 extension=php_mbstring.dll //要放在php_exif.dll前面让它先加载 ext ...

  8. Nodejs实现图片的上传、压缩预览、定时删除

    前言 我们程序员日常都会用到图片压缩,面对这么常用的功能,肯定要尝试实现一番.第一步,node基本配置 这里我们用到的是koa框架,它可是继express框架之后又一个更富有表现力.更健壮的web框架 ...

  9. Hbuilder mui 相册拍照图片上传

    http://www.bcty365.com/content-146-3648-1.html 使用流程 弹出actionSheet /*点击头像触发*/ document.getElementById ...

随机推荐

  1. 2、SpringBoot+Mybatis整合------一对一

    开发工具:STS 代码下载链接:https://github.com/theIndoorTrain/SpringBoot_Mybatis01/tree/93398da60c647573645917b2 ...

  2. 泉五培训Day1

    T1 树学 题目 [问题描述] 给定一颗 n 个点的树,树边带权,试求一个排列 P,最大化下式 其中,calc(a, b)表示树上由a到b经过的最大边权. [输入格式] 第一行一个整数 n,表示点数下 ...

  3. 基于Ceph分布式集群实现docker跨主机共享数据卷

    上篇文章介绍了如何使用docker部署Ceph分布式存储集群,本篇在此基础之上,介绍如何基于Ceph分布式存储集群实现docker跨主机共享数据卷. 1.环境准备 在原来的环境基础之上,新增一台cen ...

  4. spring-mybatis整合异常

    Failed to read artifact descriptor for XXXXXX:jar:XXXX.RELEAS 原因是maven的本地仓库没有设置好.在别处拷贝过来的项目会有自己的仓库位置 ...

  5. node服务端渲染(完整demo)

    简介 nodejs搭建多页面服务端渲染 技术点 koa 搭建服务 koa-router 创建页面路由 nunjucks 模板引擎组合html webpack打包多页面 node端异步请求 服务端日志打 ...

  6. linux系统的启动过程简要分析

    接触linux系统运维已经好几年了,常常被问到linux系统启动流程问题,刚好今天有空来梳理下这个过程:一般来说,所有的操作系统的启动流程基本就是: 总的来说,linux系统启动流程可以简单总结为以下 ...

  7. python-无参函数

    #!/usr/local/bin/python3 # -*- coding:utf-8 -*- ''' #-----------定义函数---------- def func1(): "te ...

  8. python——闰年的判断

    写一个程序,判断给定年份是否为闰年. 这样定义闰年的:能被4整除但不能被100整除,或者能被400整除都是闰年. while(1): year = input("请输入一个年份,让我判断一下 ...

  9. Android 数据库的线程合作

    前言:之前琢磨了很多线程相关的东西,一直摸不着头脑,直到学到了数据库,终于发现世界原来如此美好,任何事物都有存在的理由. 1.主线程,我把它比作长江,作为母亲河的长江,想必大家每个人都不会很陌生. 2 ...

  10. python协程和IO多路复用

     协程介绍                                                                                                ...