获取微信上传的图片(公众号)
2020-07-07 本文已影响0人
敲代码的小仙女
代码
<?php
namespace app\hryh\controller;
use WechatSDK\Wechat as wechatModel;
class Image extends \app\hryh\controller\Base
{
public static $weObj;
public static function getImage($id,$media_id)
{
$wechat = config("wechat");
$options = array(
'appid' => $wechat['appkey'],
'appsecret' => $wechat['appsecret'],
);
self::$weObj = new wechatModel($options);
$img_content = self::$weObj->getMedia($media_id);
if(!$img_content){
ajaxError('图片上传失败,请重试!');
}
$myImg = ROOT_PATH . 'public/uploads/image/user_'.self::$userInfo['number'].'.jpg';
//获取图片
$res = self::saveWeixinFile($myImg,$img_content);
//判断图片是否旋转(苹果原相机上传的图片裁剪会自动旋转)
$Orientation = self::updateImg($myImg);
//裁剪
$image = \think\Image::open($myImg);
$image->thumb(276,368, \think\Image::THUMB_CENTER)->save($myImg);
$pic_url = config("API_URL")."/uploads/image/user_".self::$userInfo['number'].".jpg?v=".time();
return $pic_url;
}
//保存图片到本地
public static function saveWeixinFile($filename, $filecontent)
{
$local_file = fopen($filename, 'w');
if (false !== $local_file){
if (false !== fwrite($local_file, $filecontent)){
fclose($local_file);
}
}
}
//判断图片是否旋转
public static function updateImg($str)
{
// $str = '文件路径';
try{
$savePath=$str;
$image = imagecreatefromstring(file_get_contents($str));
$exif = exif_read_data($str);
if($exif){
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 8:
$image = imagerotate($image, 90, 0);
break;
case 3:
$image = imagerotate($image, 180, 0);
break;
case 6:
$image = imagerotate($image, -90, 0);
break;
}
imagejpeg($image, $savePath);
imagedestroy($image);
}
}
addLog("***** Orientation *****");
addLog("data:".$exif['Orientation']);
}catch (Exception $e){
$exif['Orientation'] = null;
}
return $exif['Orientation'];
}
}