Skip to main content

Function to Read an image and display it in Magento2 action

Function to Read an image and display it in Magento2 action

here is a Function to Read an image and display it in Magento2 action Sometime you will need to have a dynamic image even you change the image with the same name, but in some server the cache of the browser will still display the old image

 

using this code you can display the image in a dynamic way

 

 // Get Magento media directory path
        $directoryList = $this->objectManager->get(\Magento\Framework\Filesystem\DirectoryList::class);
        $mediaPath = $directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
// Define the image directory
        $imageDir = $mediaPath . DIRECTORY_SEPARATOR . 'wysiwyg';
// Get image filename from URL parameter (secure)
        $imageFile = isset($_GET['img']) ? basename($_GET['img']) : 'default.jpg';
// Allow only specific image formats
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
        $fileExtension = strtolower(pathinfo($imageFile, PATHINFO_EXTENSION));
        if (!in_array($fileExtension, $allowedExtensions)) {
            die("Invalid file type!");
        }
// Get real path and validate access
        $imagePath = realpath($imageDir . DIRECTORY_SEPARATOR . $imageFile);
        if (!$imagePath || strpos($imagePath, $imageDir) !== 0 || !file_exists($imagePath)) {
            die("File not found!");
        }
// Get MIME type
        $mimeType = mime_content_type($imagePath);
// Read image data
        $imageData = file_get_contents($imagePath);
// Output the raw image
        header("Content-Type: $mimeType");
        echo $imageData;

and I have these SEO errors FeedbackThe keyphrase is over 10 words, a keyphrase should be shorter. Bad SEO scoreYou're linking to another page with the focus keyword you want this page to rank for. Consider changing that if you truly want this page to rank. Bad SEO scoreThe focus keyword doesn't appear in the first paragraph of the copy. Make sure the topic is clear immediately. Bad SEO scoreA meta description has been specified, but it does not contain the focus keyword. Bad SEO scoreNo images appear in this page, consider adding some as appropriate. OK SEO scoreNo outbound links appear in this page, consider adding some as appropriate. OK SEO scoreThe SEO title is wider than the viewable limit. OK SEO scoreThe focus keyword does not appear in the URL for this page. If you decide to rename the URL be sure to check the old URL 301 redirects to the new one!