Is it possible to retrieve an Image and/or File Object by its ID?

SilverStripe 4

Is it possible to retrieve an image object by its ID? If so, is it then possible to retrieve its metadata? If so, what is the best way to obtain the ID?

I know that I can use a has_one or has_many for images and files to associate with dataobjects, but the data is populated from an uploaded CSV. Further updates will also be done through upload of a CSV.

The original plan was to use the image/file path, but that isn’t optimal. I thought using the image ID as a reference to the images/files would work better, since if any metadata changes, I can still reference the same file through the ID.

Thanks.

If $image is an instance of Image and it has been written to the database you can access the ID with $image->ID (same is true for any subclass of DataObject).

To fetch an Image by ID you can do Image::get()->byID($id)

Thanks. Worked like a charm.

Sorry guys, but It’s not working for me. I am currently using Silverstripe 4.1 and I am trying to retrieve an image from the database and it always returns null.
When I go to the database I see the file reference in the File table. Here is the File table content for the file I was trying to retrieve:

ID ClassName LastEdited Created Name Title ShowInSearch CanViewType CanEditType Version ParentID OwnerID FileHash FileFilename FileVariant
2583 SilverStripe\Assets\Image 2018-11-08 21:05:48 2018-11-08 21:05:48 logo-v5.png logo-v5 1 Inherit Inherit 1 1753 10 9e6faa29b752294d2e623bd83b17660df123af62 images/logo-v5.png NULL

Here are the way I tried:
File::get()->byID(2583);
Image::get()->byID(2583);
File::get_by_id(‘SilverStripe\Assets\Image’, 2583);

In all cases is returning null. Do you know what I am missing here?

Have you published that image?

I created a field in administration page and the upload field is working. At least the file reference is going to the database and is there when I reload the page:

class MySiteConfigExtension extends DataExtension
{
    private static $db = [
        'LinkURL' => 'Text',
        'LinkLabel' => 'Varchar(255)',
    ];

    private static $has_one = [
        'Logo' => Image::class,
    ];

    private static $owns = [
        'Logo'
    ];


    public function updateCMSFields(FieldList $fields)
    {
        //Define Fields
       
        $LinkURL = TextField::create("LinkURL", "Link URL")->setDescription('Mortgage     bank link URL.');
        $LinkLabel = TextField::create("LinkLabel", "Link     Label")->setDescription('Button label.');
        $Logo = UploadField::create('Logo', 'Link Bank     Logo')->setFolderName('images/')->setAllowedFileCategories(['image']);

        $fields->addFieldsToTab('Root.SiteLink', array(
            $LinkURL,
            $LinkLabel,
            $Logo,
        ));
        return $fields;
    }
}