php base64压缩图片上传,thinkphp 使用base64上传图片并自动压缩图片

thinkphp使用base64上传,并自动压缩

> 前端在上传前应该按质量压缩下,这样在效率上快很多,不能全依靠后端压缩。

压缩时如宽度大于800,会等比例缩小为800,如宽度小于800,则不操作。

```php

/**

* 上传图片

*/

public function uploadImg()

{

//防止内存溢出

ini_set('memory_limit', '256M');

//忽略图片警告

ini_set('gd.jpeg_ignore_warning', 1);

$param = $this->param;

$img = $param['imgPath'];

$type = $param['type'];

if (empty($img) || !in_array($type, array('head_img', 'banner', 'types', 'product', 'ad_matrials', 'news', 'icon', 'activity', 'editor', 'develop', 'honor', 'leader_care', 'office'))) {

return $this->err('参数错误!');

}

$base64 = str_replace('data:image/jpeg;base64,', '', $img);

$base64 = str_replace('=', '', $base64);

$img_len = strlen($base64);

$file_size = $img_len - ($img_len / 8) * 2;

if ($file_size > (1024 * 1024 * 10)) {

$file_size = number_format(($file_size / 1024 / 1024), 2) . 'mb';

return $this->err("允许上传的文件最大不超过10M,当前文件" . $file_size . "!");

}

//匹配出图片的格式

if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)) {

$t = $result[2];

$path = config('app_file_path') . "/upload/admin/" . $type . "/" . date('Ymd') . "/";

if (!file_exists($path)) {

//检查是否有该文件夹,如果没有就创建,并给予最高权限

mkdir($path, 0777, true);

}

$t = $t == 'jpeg' ? 'jpg' : $t;

$new_file = $path . Date('YmdHis') . rand(10, 99) . "." . $t;

if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)))) {

if ($result !== false) {

//生成800宽度的缩略图

$image = Image::open($new_file);

$result = $image->thumb(800, 100000, Image::THUMB_SCALING)->save($new_file);

$file_path = str_replace(config('app_file_path'), "", $new_file);

$backData['url'] = $file_path;

return $this->suc($backData, '', config('app_img_root'));

} else {

return $this->err('服务器繁忙!');

}

} else {

return $this->err('上传失败!');

}

} else {

return $this->err('上传失败!');

}

}

```

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值