php 将图片转为base_64位编码格式以及将base64位普通编码转为图片保存到文件中

public function timeceshi()
{
    // 书写图片所在域名或者地址
    $img = 'http://www.lh.com/uploads/20181119/8760db7392380af20342e07813ad079.jpg';
    // file_get_contents()函数将所在文件读入一个字符串中,即将图片转化为普通字符串
    // base64_encode()函数将图片转化为base64位格式
    $base64_img = base64_encode(file_get_contents($img));

    // base64位编码转为图片保存在文件中
    // 设置生成的图片名称
    $imageName = "25220_".date("His",time())."_".rand(1111,9999).'.png';
    // 判断是否有逗号 如果有就截取后半部分
    if (strstr($base64_img,",")){
         $base64_img = explode(',',$base64_img);
         $base64_img = $base64_img[1];
    }
    // 设置图片保存路径
    $path = "./uploads/code/".date("Ymd",time());
    // 判断目录是否存在 不存在就创建 并赋予777权限
    if (!is_dir($path)){
         mkdir($path,0777,true);
    }
    // 拼接路径和图片名称
    $imageSrc= $path."/". $imageName;
     // 生成图片 返回的是字节数
     $r = file_put_contents($imageSrc, base64_decode($base64_img));
    
}
### 如何压缩 Base64 编码图片 当处理 Base64 编码图片时,可以采用多种方法来减少其大小。一种常见的做法是在 PHP 中先将 Base64 字符串转换成二进制数据,再利用图像处理库对其进行压缩。 #### 将 Base64 图片字符串转为临时文件并压缩 通过创建一个临时文件存储原始图片,之后使用 GD 库或其他图形扩展调整质量或尺寸达到压缩效果: ```php function compressBase64Image($base64String, $outputPath, $quality = 80){ // 移除 base64 前缀 'data:image/jpeg;base64,' 或者其他类似的前缀 preg_match('/^data:(.*?);base64,(.*?)$/mi', $base64String, $matches); if (isset($matches[2])) { $imageData = base64_decode($matches[2]); file_put_contents('temp_image.jpg', $imageData); list($width, $height) = getimagesize('temp_image.jpg'); $newWidth = $width * 0.7; // 调整宽度至原图70% $newHeight = $height * 0.7; $srcImg = imagecreatefromjpeg('temp_image.jpg'); $dstImg = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); imagejpeg($dstImg, $outputPath, $quality); imagedestroy($srcImg); imagedestroy($dstImg); unlink('temp_image.jpg'); // 删除临时文件 return true; } } ``` 此函数接收三个参数:`$base64String` 是包含图片数据 URI 的字符串;`$outputPath` 表示目标路径用于保存最终被压缩后的图片;可选参数 `$quality` 控制 JPEG 输出的质量,默认设置为 80%[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值