Magento: Images and the product_media API


I built an image importer and have a few notes about using Magento’s Product Images API. I have a large number of images from our paper catalog, and also from our old cart solution. Thousands of images, really. A lot.

So I built a little php ditty that would recurse directories, looking for the best image it could find. In my old cart, this was an image called 0500.jpg. Directories are constructed like this: /wpi/s/sku9999/. When I find 0500.jpg under this directory I put it into magento using the Product Images API. I found out a couple of things:

Notes from the Field

1. The API is hardcoded to call the uploaded file “image_XX.(mime type).” I could see no way to change that; the net effect is that every image you add to Magento via the Product Images API ends up in media/catalog/product/i/m.

In order to more evenly distribute my product images across directories, I hacked the Core API. I know it’s a no-no, but I’ll hack it right back. I only needed it for this mass upload – 5,000+ items. Dear Magento: Please make my hack an option – or even permanent change – to Magento.

In app/code/core/Mage/Catalog/Model/Product/Attribute/Media/Api.php, At line 137, I changed this:

$fileName  = 'image.' . $this->_mimeTypes[$data['file']['mime']];

To this:

$fileName  = $productId.'.'. $this->_mimeTypes[$data['file']['mime']];

2. The Administration Backend disassociates an image from its item when you say “Remove,” but it does not actually delete it from disk.

I Call the Magento Product API – at Last

Here’s the function I called to do the upload. It’s essentially the same as teh Product Images API documentation example, except that I am using a single image for all “types.” It’s a bit fuzzy in the documentation, but using this function, you’ll end up with 1 image for Base Image, Small Image and Thumbnail Image. I’m printing out some extra debugging information as well.

uploadImage( $sku, $imagePath ) {
    global $proxy;
    global $sessionId;
    $sku = strtoupper($sku );
    $newImage = array(
        'file' => array(
            'content' => base64_encode(file_get_contents($imagePath)),
            'mime'    => 'image/jpeg'
        'label'    => "Item:" . $sku,
        'position' => 0,
        'types'    => array('image', 'small_image', 'thumbnail' ),
        'exclude'  => 0
    try {
        $imageFilename = $proxy->call($sessionId, 'product_media.create', array($sku, $newImage));
        var_dump($proxy->call($sessionId, 'product_media.list', $sku));
    catch(Exception $e) {
        print( "Error assigning image to $sku: " . $e->getMessage() . "\n" );

See ya next time!

Facebook comments: