public function test_generate_image_thumbnail_from_string() { global $CFG; require_once $CFG->libdir . '/gdlib.php'; // Test with meaningless data. // First empty values. $this->assertFalse(generate_image_thumbnail_from_string('', 24, 24)); $this->assertFalse(generate_image_thumbnail_from_string('invalid', 0, 24)); $this->assertFalse(generate_image_thumbnail_from_string('invalid', 24, 0)); // Now an invalid string. $this->assertFalse(generate_image_thumbnail_from_string('invalid', 24, 24)); // Now use a fixture. $pngpath = $this->fixturepath . 'gd-logo.png'; $pngdata = file_get_contents($pngpath); $pngthumb = generate_image_thumbnail_from_string($pngdata, 24, 24); $this->assertTrue(is_string($pngthumb)); // And check that the generated image was of the correct proportions and mimetype. $imageinfo = getimagesizefromstring($pngthumb); $this->assertEquals(24, $imageinfo[0]); $this->assertEquals(24, $imageinfo[1]); $this->assertEquals('image/png', $imageinfo['mime']); }
/** * Returns the stored thumbnail file, generates it if not present. * * @param string $filepath current path in repository (dir and filename) * @param string $thumbsize 'thumb' or 'icon' * @return null|stored_file */ public function get_thumbnail($filepath, $thumbsize) { global $CFG; $filepath = trim($filepath, '/'); $origfile = $this->get_rootpath() . $filepath; // As thumbnail filename we use original file content hash. if (!$this->is_in_repository($filepath) || !($filecontents = @file_get_contents($origfile))) { // File is not found or is not readable. return null; } $filename = sha1($filecontents); // Try to get generated thumbnail for this file. $fs = get_file_storage(); if (!($file = $fs->get_file(SYSCONTEXTID, 'repository_filesystem', $thumbsize, $this->id, '/' . $filepath . '/', $filename))) { // Thumbnail not found . Generate and store thumbnail. require_once $CFG->libdir . '/gdlib.php'; if ($thumbsize === 'thumb') { $size = 90; } else { $size = 24; } if (!($data = generate_image_thumbnail_from_string($filecontents, $size, $size))) { // Generation failed. return null; } $record = array('contextid' => SYSCONTEXTID, 'component' => 'repository_filesystem', 'filearea' => $thumbsize, 'itemid' => $this->id, 'filepath' => '/' . $filepath . '/', 'filename' => $filename); $file = $fs->create_file_from_string($record, $data); } return $file; }