【问题标题】:save image stream to laravel将图像流保存到 laravel
【发布时间】:2019-11-02 20:43:25
【问题描述】:

在我的 Laravel 控制器中,我尝试获取一串 png 图像数据,然后使用 put 将其保存为 png 到存储中:

$image_string = $request->get('image_string', false);
$filename = 'temp_image';

if ($image_string) {
    $resource = imagecreatefromstring($image_string);
    Log::debug("Storing image");
    if ($resource !== false) {
        Storage::put('public/' . $filename . '.png', imagepng($resource));
    } else {
        Log::error("Failed to get resource from string");
    }
}

如果我只拆分 imagecreatefromstring($image_string)imagepng($resource) 部分,则文件将按预期创建。但是在Storage::put 的某个地方,图像要么损坏要么丢失,因为虽然存在具有正确文件名和扩展名的图像,但它没有数据并且在查看时显示为黑框。

我需要以其他方式处理图像存储例程吗?

【问题讨论】:

  • 试试Storage::putFileAs('public', imagepng($resource), $filename.'.png');
  • @sykez 抛出错误:Call to a member function getRealPath() on boolean in laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php
  • 啊,我猜是因为它不是 File 实例。或许您可以提供imagepng()imagecreatefromstring() 的代码。无论哪种方式,正如 Stefano 所提到的,您应该使用干预来处理所有与图像相关的功能。特别是如果它涉及转换格式和调整大小。此外,如果您正在处理图片上传,您应该只使用Storage::putFile('public', $request->image);
  • @sykez imagepngimagecreatefromstring 在 PHP (with php-gd) -- php.net/manual/en/function.imagecreatefromstring.php

标签: php laravel laravel-5 png


【解决方案1】:

我认为问题在于您不能以这种方式更改每种图像的图像扩展名。

检查这个 PHP 图像处理库:http://image.intervention.io/getting_started/introduction

你可以很容易地将它集成到 Laravel 中,并且有一个 API 可以转换不同格式的图像:http://image.intervention.io/api/encode

【讨论】:

    【解决方案2】:

    感谢@Stefano Cortese 和@sykez——解决方案融合了这两种想法。

    $image_string = $request->get('image_string', false);
    $filename = 'temp_image';
    
    if ($image_string) {
        $resource = Image::make($image_string)->encode('png');
        Log::debug("Storing image");
        if ($resource !== false) {
            Storage::put("public/{$filename}.png", (string) $resource);
        } else {
           Log::error("Failed to get resource from string");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2020-08-22
      • 2017-07-26
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多