Magento – magento2 make image base via REST API

magento2product-imagesrest

How can I make an image of a product the base image ? I tought setting the position would be enough but that's not true.

I create my products via the REST api , this works fine.

The images are uploaded correct.

But I don't know how to tag an image as the base image. When I have multiple images it is always the last images that is tagged as base automaticly, I don't want that. How could I set that in my array?

$product = [
    "sku" => str_replace(' ', '-', $data['name']),
    "name" => $data['name'],
    "type_id" => 'configurable',
    "price" => 0,
    'attribute_set_id' => 9, // default
    "extension_attributes" => [],
    "custom_attributes" => [],
    'media_gallery_entries' => $this->getMediaGalleryEntries($data)
];

function getMediaGalleryEntries($data)
{
    $image = 'path/to/my/image';

    $entries[] = [
        'position' => $iterator,
        'media_type' => 'image',
        'disabled' => false,
        'label' => '',
        'types' => ['image', 'small_image', 'thumbnail'],
        'content' => [
            'type' => 'image/jpeg',
            'name' => pathinfo($image,PATHINFO_FILENAME).'.'.pathinfo($image, PATHINFO_EXTENSION),
            'base64_encoded_data' => base64_encode(file_get_contents($image)),
        ]
    ];

    return $entries;
}

Best Answer

I've solved it like this:

 foreach($images as $image) {
    $entries[] = [
        'position' => $iterator,
        'media_type' => 'image',
        'disabled' => false,
        'label' => '',
        'types' => ($iterator == 1 ? ['image','small_image','thumbnail'] : []),
        'content' => [
            'type' => 'image/jpeg',
            'name' => pathinfo($image,PATHINFO_FILENAME).'.'.pathinfo($image, PATHINFO_EXTENSION),
            'base64_encoded_data' => base64_encode(file_get_contents($image)),
        ]
    ];
    $iterator++;
}

Types should only be assigned to the first image.This is the image I want as base image.

Related Topic