Laravel Api返回图像为64字符串

时间:2018-03-12 21:59:03

标签: php image laravel

在我的api路径中,我调用了这个方法,它返回一个包含所有数据的Collection。

public function getAllGames()
{
    return $this->game->all();
}

数据看起来像这样

[
    {
        "id": 1,
        "title": "Dragonball",
        "description": "asdasd",
        "image": "db.png",
        "release_date": "2018-03-28",
        "release_status": 0,
        "created_at": "2018-03-12 21:28:49",
        "updated_at": "2018-03-12 21:28:49"
    },
]

而不是图像名称我想将图像作为基本64字符串返回。

我创建了一个帮助器类,其中包含一个将Image从路径转换为base 64字符串的方法:

class ImageHelper {

    public static function imageToBase64($path) {
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

        return $base64;
    }

}

现在我不确定是否必须修改Collection,以便我的数据看起来像这样:

[
    {
        "id": 1,
        "title": "Dragonball",
        "description": "asdasd",
        "image": "daoisdboi3h28dwqd..", // base64string
        "release_date": "2018-03-28",
        "release_status": 0,
        "created_at": "2018-03-12 21:28:49",
        "updated_at": "2018-03-12 21:28:49"
    },
]

当然,我有一个以上的数据。

修改

我尝试使用下面的建议来使用访问器,但它没有用到我有一个

  

file_get_contents():文件名不能为空

错误

我的模态现在看起来像这样:

class Game extends Model
{
    protected $table = 'games';

    protected $fillable = [
        'title', 'description', 'image', 'release_date', 'release_status'
    ];

    protected $appends = ['imageString'];

    public function getImageStringAttribute() {
        $type = pathinfo($this->image, PATHINFO_EXTENSION);
        $data = file_get_contents($this->image);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
        return $base64;
    }

}

在我的ApiController中,我这样做:

class ApiController extends Controller
{
    protected $game;

    public function __construct(Game $game)
    {
        $this->game = $game;
    }

    # TODO
    # return image as base64 string
    public function getAllGames()
    {
        return $this->game->getImageStringAttribute();
    }
}

1 个答案:

答案 0 :(得分:2)

使用访问者:https://laravel.com/docs/5.6/eloquent-mutators#defining-an-accessor

将此添加到您的模型中:

protected $appends = ['imageString'];

public function getImageStringAttribute() {
    $type = pathinfo($this->image, PATHINFO_EXTENSION);
    $data = file_get_contents($this->image);
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
    return $base64;
}