【问题标题】:Generate image from text response with correct extension从具有正确扩展名的文本响应生成图像
【发布时间】:2019-06-30 02:36:47
【问题描述】:
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://stagingadmin.zenpepper.com/image/5b1a35e54a77da5969f1f98d?token=HIDDEN",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_POSTFIELDS => "",
  CURLOPT_HTTPHEADER => array(
    "Postman-Token: HIDDEN",
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

我有一个 api 调用将图像作为文本返回,并且该图像可以转换为图像。但我想在 laravel 中以正确的扩展名保存该图像

目前我有以下代码,但我想尝试更好的解决方案。

if (!file_exists(public_path() . '/images/' . $image_id . '.png')) {

    if (strpos($response, 'PNG') !== false || strpos($response, 'png') !== false) {
        Image::make($response)->save(public_path('images/' . $image_id . ".png"));
    }
}

if (!file_exists(public_path() . '/images/' . $image_id . '.jpg')) {

    if (strpos($response, 'jpg') !== false || strpos($response, 'JPG') !== false) {
        Image::make($response)->save(public_path('images/' . $image_id . ".jpg"));
    }
}

【问题讨论】:

    标签: php laravel image api mime


    【解决方案1】:

    在 Laravel 中保存文件有更好的方法。

    if($response)
       {
          $path = 'images/' . $image_id;
          $fileName = str_replace(' ', '_', response->getClientOriginalName());
          $response->storeAs($path,$fileName);
       }
    

    了解更多Laravel File Storage

    【讨论】:

      【解决方案2】:

      我认为在Laravel 中使用文件存储驱动程序是一种更好的方式。 https://laravel.com/docs/5.7/filesystem

      对于确定的文件类型,可以阅读MIME类型。

      【讨论】:

        猜你喜欢
        • 2021-01-25
        • 2015-07-24
        • 1970-01-01
        • 2014-05-05
        • 1970-01-01
        • 2013-01-11
        • 2013-06-02
        • 2013-05-20
        相关资源
        最近更新 更多