PHP 把图片转换成base64编码格式

图片转换成base64编码问题

图片的保存和传输有些不是很方便,这是可以转成字符串。例如远程下载图片,一般是没有权限操作的。
常用的有两种方案:

  1. 把远程图片下载到当前服务器,再给当前服务器的图片地址前端下载,下载的是当前服务器的图片,绕过跨源问题;
  2. 把远程图片转成base64编码格式,传输图片字符串给前端,前端转换成图片。

这里介绍第二种方案。

PHP 实现

<?php

/**
 * 把图片转成base64编码
 * @param $file string 图片路径
 * @return array|string
 */
public function imgToBase64($file)
{
    if($fp = fopen($file,"rb", 0)) {
        // 获取图片文件大小
        $header_array = get_headers($file,true);
        $size = $header_array['Content-Length'];

        // 获取类型
        $img_info = getimagesize($file);

        // 类型默认png
        $img_type = 'png';
        // 判读图片类型
        switch ($img_info[2]) {
            case 1: $img_type = "gif";
                break;
            case 2: $img_type = "jpg";
                break;
            case 3: $img_type = "png";
                break;
        }

        $gambar = fread($fp, $size);
        fclose($fp);

        $base64Img = chunk_split(base64_encode($gambar));

        // 拼上文件类型和格式,解码时有些需要把这两个东西去掉,有些不需要,可以根据自己的场景调整,避免出错
        // 测试地址:http://tool.chinaz.com/tools/imgtobase/
        $imgContent = 'data:image/' . $img_type . ';base64,' . $base64Img;

        return ['imgContent' => $imgContent];
    }else{

        return '下载图片失败,请重试';
    }
}

//************使用************
// 图片路径
$file = '123.png';
$imgContent = $this->imgToBase64($file);

print_r($imgContent);

遇到问题
下面说下我遇到的问题,图片有本地和远程两种情况,有些图片处理函数无法获取远程图片的信息,例如很多教程说的获取图片文件大小的函数

// 获取文件大小
filesize($ImageFile)

我试了下,获取远程的会失败,本地的就行,这里的写法是这种

// 获取图片文件大小
$header_array = get_headers($file,true);
$size = $header_array['Content-Length'];

下面介绍其他的获取远程文件大小的方法,不限于图片

<?php
// 1、第一种,直接抓取文件,计算长度
$file = file_get_contents($url);
echo strlen($file);

// 2、第二种,获取头部的长度参数
$header_array = get_headers($url, true);
$size = $header_array['Content-Length'];
echo $size;

// 3、第三种,使用php curl 来获取远程文件大小
/**
 * 获取远程文件大小函数,返回文件大小单位为字节
 * @param $file string 图片路径
 * @return array|string
 */
function remote_filesize($url, $user = "", $pw = "")
{
    ob_start();
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
 
    if(!empty($user) && !empty($pw))
    {
        $headers = array('Authorization: Basic ' .  base64_encode("$user:$pw"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
 
    $ok = curl_exec($ch);
    curl_close($ch);
    $head = ob_get_contents();
    ob_end_clean();
 
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $head, $matches);
 
    return isset($matches[1]) ? $matches[1] . " 字节" : "unknown";
}

// 实例测试
echo remote_filesize("http://www.runoob.com/wp-content/themes/runoob/assets/img/runoob-logo@2x.png");
A free, fully-featured, and extensible tool for automating any web or desktop application. Automation software that drives user interface like a human. How does it work? With UiPath you can create windows automation software that manipulates applications, akin to how a human uses the computer. You can create an automation robot as easy as you train a human user, by simply indicating on the screen what the steps of the automation are and assembling them into a visual flowchart diagram. Anyone can understand a flowchart, and automation is just as intuitive. A free, fully-featured, and extensible tool for automating any web or desktop application. UiPath Studio Community is free for individual developers, small professional teams, education and training purposes UiPath enables organizations to configure software robots that automate manual, repetitive rules-based tasks at a fraction of the cost of their human equivalent, and integrate without disruption the legacy system. Desktop Automation. UiPath Studio introduces a visual, declarative way of describing how to automate a process, and you can use it in the same way you use a Visio diagram. When working with the presentation layer of other apps, you simply indicate on the screen what operation you need to perform. UiPath understands the UI at the logical control level and does not rely on the position of elements on screen. This makes automation much more reliable and independent of screen-size and resolution. Most advanced Screen Scraping Technology. UiPath features an innovative technique for extracting text from running apps, even if they are hidden or covered by another app. Web scraping is a premier feature of the screen-scraping landscape, as there are dedicated methods for extracting pattern-based data that span multiple web pages. Macro Recorder - The world's most advanced windows macro recorder. You create a Windows macro with the UiPath recorder in the same way that you would train a human user to use an application. Indicate directly on the screen where to click, type, select, copy, paste, or perform any other common action and UiPath will generate a visual script like in the image below. UiPath's macro recorder allows you to record mouse events and keyboard activities to generate automation scripts. The arrangement of the activities is on the sequence of actions being performed in the screen. This sequence is saved in your workflow and you can use later playback the recorded actions.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值