Have you found stored_file->generate_image_thumbnail()
? You have to specify both width and height which means you need to work out the aspect ratio before calling this. Alternatively, you can call resize_image()
(in lib/gdlib.php
) and only pass the width or height and the aspect ratio is maintained.
For a plugin we were working on I added the following to generate course image thumbnails:
$courseinlist = new \core_course_list_element($course);
foreach ($courseinlist->get_course_overviewfiles() as $file) {
if ($file->is_valid_image()) {
$thumbnail = $fs->get_file($context->id, 'report_myreport', 'course_thumbnail', $course->id, '/', 't_' . $file->get_filename());
if (!$thumbnail) {
$imagepath = $filesystem->get_local_path_from_storedfile($file);
if ($data = resize_image($imagepath, null, 48)) {
$filerecord = new \stdClass();
$filerecord->contextid = $context->id;
$filerecord->component = 'report_myreport';
$filerecord->filearea = 'course_thumbnail';
$filerecord->itemid = $course->id;
$filerecord->filepath = '/';
$filerecord->filename = 't_'. $file->get_filename();
$thumbnail = $fs->create_file_from_string($filerecord, $data);
}
}
if ($thumbnail) {
return moodle_url::make_pluginfile_url($context->id,
'report_myreport', 'course_thumbnail',
null, '/', $thumbnail->get_filename());
}
}
}
This was just for course images used for the plugin, not for the course cards on the dashboard.
But it only saved a tiny amount of time since the file transfer of even quite big image files wasn't such a major factor compared with the number of images being transferred (in my testing at least). And since the browser should cache course images this further diminished any performance improvement from reducing the file sizes.