Back to Integrations

Magento Integration

E-commerce

Enterprise product image processing

Magento 2 Module

PHP Observer for Image Upload
<?php
// Observer/ProductImageEnhance.php
namespace Vendor\ButterflyAPI\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\HTTP\Client\Curl;

class ProductImageEnhance implements ObserverInterface
{
    protected $curl;
    
    public function __construct(Curl $curl) {
        $this->curl = $curl;
    }
    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getProduct();
        $mediaGallery = $product->getMediaGalleryImages();
        
        foreach ($mediaGallery as $image) {
            $imageUrl = $image->getUrl();
            
            $this->curl->setHeaders([
                'Authorization' => 'Bearer ' . $this->getApiKey(),
                'Content-Type' => 'application/json'
            ]);
            
            $this->curl->post(
                'https://butterflyapi.com/api/v1/run',
                json_encode([
                    'api' => 'image-enhance',
                    'input' => ['image_url' => $imageUrl, 'scale' => 2]
                ])
            );
            
            $result = json_decode($this->curl->getBody(), true);
            
            // Update image with enhanced version
            if (isset($result['output']['image_url'])) {
                $this->updateProductImage($product, $image, $result['output']['image_url']);
            }
        }
    }
}