【问题标题】:Laravel 9: Converting An Image From Bytes To Jpeg From Storage DirectoryLaravel 9:将图像从存储目录中的字节转换为 Jpeg
【发布时间】:2023-02-06 19:29:40
【问题描述】:

我正在使用 Laravel 9,我想显示存储在存储/应用程序/化身.

所以我在 Blade 上尝试了这个:

{{ \App\Http\HelperClasses\ImageHelper::admAvatar() }}

这是 ImageHelper 类:

namespace App\Http\HelperClasses;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;

class ImageHelper
{
    public static function admAvatar()
    {
        $content = Storage::get('avatars/profile.png');

        return Response::make($content)->header('content-type','image/jpeg');
    }
}

所以我尝试从 profile.png 制作图像并最终返回它。

但问题是它没有显示任何内容!

当我dd(Response::make($content)->header('content-type','image/jpeg')) 时,我得到了这个:

dd($content) 的结果也是这样的:

那么我怎样才能把它正确地转换成图像呢?

【问题讨论】:

  • 你打算如何“渲染”图像?在那种前端?您可以将其转换为 base64 并尝试将其加载到 <img> 标记中,不是吗?
  • 我是这样做的 Controller: public function getFile($type, $id) { $contents = Storage::get($file_path); return response($contents, 200, $headers); } Routes: Route::get('/attachments/display/{parent_type}/{parent_id}', [App\Http\Controllers\AttachmentController::class, 'display']); HTML: &lt;img src="/attachments/display/avatar/1" /&gt;
  • @justrusty 请将其添加为答案以使其更具可读性
  • 基本上你可能只需要做&lt;img src="{{ \App\Http\HelperClasses\ImageHelper::admAvatar() }}" /&gt;

标签: php laravel laravel-9


【解决方案1】:

我是这样做的

控制器:

public function getFile($type, $id) {
    $attachment = Attachment::where([['parent_type', $type], ['parent_id', $id]])->latest()->firstOrFail();
    $headers = ['content-type' => 'image/jpeg'];
    $contents = Storage::get($attachment->file_path); 
    return response($contents, 200, $headers); 
}

路线:

Route::get('/attachments/display/{type}/{id}', [AppHttpControllersAttachmentController::class, 'display']);

HTML:

<img src="/attachments/display/avatar/1" />

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2014-05-26
    相关资源
    最近更新 更多