Загрузка изображений Prestashop через php
Необходимо создать продукты через файл PHP. Мне удалось добавить все данные о продукте кроме его фотографий (Создавал все через подключение к PhpMyAdmin). На просторах интернета нашел функцию которая добавляет изображения используя классы Престы. Это часть кода из импорта:
$image = new Image();
$image->id_product = (int) $product->id;
$image->position = Image::getHighestPosition($product->id) + 1;
$image->cover = true;
$image->add();
if (!copyImg($product->id, $image->id, $data["IMGURL"], 'products', !Tools::getValue('regenerate'))) {
$image->delete();
}
function copyImg($id_entity, $id_image, $url, $entity = 'products', $regenerate = true) {
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
$watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
switch ($entity) {
default:
case 'products':
$image_obj = new Image($id_image);
$path = $image_obj->getPathForCreation();
break;
case 'categories':
$path = _PS_CAT_IMG_DIR_ . (int) $id_entity;
break;
case 'manufacturers':
$path = _PS_MANU_IMG_DIR_ . (int) $id_entity;
break;
case 'suppliers':
$path = _PS_SUPP_IMG_DIR_ . (int) $id_entity;
break;
}
$url = str_replace(' ', '%20', trim($url));
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
if (!ImageManager::checkImageMemoryLimit($url))
return false;
// 'file_exists' doesn't work on distant file, and getimagesize makes the import slower.
// Just hide the warning, the processing will be the same.
if (Tools::copy($url, $tmpfile)) {
ImageManager::resize($tmpfile, $path . '.jpg');
$images_types = ImageType::getImagesTypes($entity);
if ($regenerate)
foreach ($images_types as $image_type) {
ImageManager::resize($tmpfile, $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
}
else {
unlink($tmpfile);
return false;
}
unlink($tmpfile);
return true;
}
Но я не до конца понимаю как его использовать, нужно подключить какие-то дополнительный файлы? И есть ли другой способ добавить фотографии в продукты Престы через свой собственный файл PHP (Все данные продукта у меня есть: ID/Название и тд)?
UPD
Немного разобрался и лучшим решением было создать свой модуль. Теперь продукт создается, но изображение продукта просто белый квадрат, а на сервере не появляется каталог который видно в ссылке если посмотреть через просмотр кода элемента этого ~белого квадрата~
Вот код модуля функции модуля которая отвечает за создание продукта:
public function processForm()
{
// Create or update product based on prodID
$output = '';
// Retrieve variables for product creation/update
$prodID = 99999; // Example prodID
$prodName = 'Sample Product'; // Example product name
$prodPrice = 10.99; // Example product price
$prodQuantity = 100; // Example product quantity
$imageURL = 'юрл фото'; // Example image URL
// Add more variables as needed
// Check if product with given prodID already exists
$existingProduct = new Product($prodID);
$productExists = Validate::isLoadedObject($existingProduct);
if ($productExists) {
// Update existing product
$existingProduct->name = $prodName;
$existingProduct->price = $prodPrice;
$existingProduct->quantity = $prodQuantity;
// Remove existing product images
$existingProduct->deleteImages();
// Update product image
if (!empty($imageURL)) {
// Save image locally
$localImagePath = dirname(__FILE__) . '/local_image.jpg';
file_put_contents($localImagePath, file_get_contents($imageURL));
// Add image to product
$this->addProductImage($localImagePath, $prodID);
// Delete local image after adding
unlink($localImagePath);
}
// Update other product attributes as needed
if ($existingProduct->save()) {
$output .= $this->displayConfirmation($this->l('Product updated successfully.'));
} else {
$output .= $this->displayError($this->l('Failed to update product.'));
}
} else {
// Create new product
$newProduct = new Product();
$newProduct->name = $prodName;
$newProduct->price = $prodPrice;
$newProduct->quantity = $prodQuantity;
// Set other product attributes as needed
if ($newProduct->save()) {
// Set product image
if (!empty($imageURL)) {
// Save image locally
$localImagePath = dirname(__FILE__) . '/local_image.jpg';
file_put_contents($localImagePath, file_get_contents($imageURL));
// Add image to product
$this->addProductImage($localImagePath, $newProduct->id);
// Delete local image after adding
unlink($localImagePath);
}
$output .= $this->displayConfirmation($this->l('New product created successfully.'));
} else {
$output .= $this->displayError($this->l('Failed to create new product.'));
}
}
return $output;
}
private function addProductImage($imagePath, $productId)
{
$image = new Image();
$image->id_product = (int)$productId;
$image->position = Image::getHighestPosition($productId) + 1;
$image->cover = 1;
if (!$image->add()) {
return false;
}
// Load the image from the specified path
$sourceImage = imagecreatefromjpeg($imagePath);
if (!$sourceImage) {
return false;
}
// Get the image dimensions
list($width, $height) = getimagesize($imagePath);
// Create a new true color image with the size of the product image
$newImage = imagecreatetruecolor($width, $height);
// Copy and resize the source image to the new image
if (!imagecopyresized($newImage, $sourceImage, 0, 0, 0, 0, $width, $height, $width, $height)) {
return false;
}
// Save the new image
if (!imagejpeg($newImage, _PS_PROD_IMG_DIR_ . $productId . '-' . $image->id . '.jpg')) {
return false;
}
return true;
}