首页 > 解决方案 > imagecolorat() 中的“资源”是什么?

问题描述

因此,在Laravel 5.7中考虑以下内容:

<?php

use Illuminate\Database\Seeder;

use App\Modules\Locations\Services\CreateMapService;
use ChristianEssl\LandmapGeneration\Struct\Color;
use App\Modules\Locations\Models\Location;

class SurfaceLocations extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $water = new Color(66, 129, 178);
        $land  = new Color(23, 132, 72);

        $createImage = new CreateMapService($land, $water, 500, 500, 'random_map');
        $createImage->generateMap('surface');

        $contents = Storage::disk('maps')->get('surface.png');

        $waterR = 66;
        $waterG = 129;
        $waterB = 178;

        for ($x = 0; $x <= 500; $x++) {
            for($y = 0; $y <= 500; $y++) {
                $rgb = imagecolorat($contents, $x, $y);

                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;


                if ($r === $waterR && $g === $waterG && $b === $waterB) {
                    Location::create([
                        'x' => $x,
                        'y' => $y,
                        'is_water' => true
                    ]);
                } else {
                    Location::create([
                        'x' => $x,
                        'y' => $y,
                        'is_water' => false
                    ]);
                }
            }
        }
    }
}

所以我创建地图并保存它,然后我尝试获取图像的内容,然后将其传递给 imagecolor,遍历图像的每个 x、y 位置,查看水 rgb 是否与输出 rgb 匹配。

但我得到了错误:

imagecolorat() 期望参数 1 是资源,给定字符串

所以我查找了这个资源是什么并得到了这个imagecreatetruecolor()功能,但我不确定如何将它与我创建和保存的图像一起使用。

关于如何将此功能与现有图像一起使用的任何想法?文档,使用创建图像的示例。

标签: phplaravelimage

解决方案


你需要修复这条线

$contents = Storage::disk('maps')->get('surface.png');

成为

$contents = imagecreatefromstring( Storage::disk('maps')->get('surface.png') );

并且您的代码将起作用...因为在您执行此操作的过程中,您将 $contents 文件 surface.png 的内容放入不是图像资源...

只需将 $contents 重命名为更直观的名称,因为那是图像资源,不再是内容


推荐阅读