Мы не предоставляем техническую поддержку в форуме.
Форум создан для общения пользователей. Чтобы обратиться в службу поддержки, воспользуйтесь формой отправки запроса.

#1 2009-02-12 10:12

Deveruchi
Пользователь

Добавление водяных знаков на картинки товаров

Мне необходимо добавить водяной знак на картинку. Добавить я могу, но в какой файл добавить скриптик? Собственно вопрос, в каком файле располагается функция добавления картинок в базу?

Неактивен

 

#2 2009-02-23 14:48

rawman
Пользователь

Re: Добавление водяных знаков на картинки товаров

поделись что за скрипт, мне тоже надо

Неактивен

 

#3 2009-02-24 03:08

Shaman
Пользователь

Re: Добавление водяных знаков на картинки товаров

вот код, разбирайтесь.
в html коде ссылка на картинку вида image.php?id=ид_картинки&t=размер

image.php:

Код:

<?
include_once("cfg/connect.inc.php");
include_once("class_watermark.php");

$watermark = new watermark();

$id=strip_tags( $_GET['id'] );
$t=strip_tags( $_GET['t'] );

mysql_connect(DB_HOST, DB_USER, DB_PASS) or die ( "Невозможно подключиться к базе данных" );
mysql_select_db(DB_NAME) or die ( "Невозможно подключиться к таблице" );
$r=mysql_query("SELECT * FROM ".PRODUCT_PICTURES." WHERE photoID='$id'");

switch( $t ) {
case 's': $img="products_pictures/".mysql_result($r, 0, 'thumbnail'); break;
case 'b': $img="products_pictures/".mysql_result($r, 0, 'enlarged'); break;
default: $img="products_pictures/".mysql_result($r, 0, 'filename'); break;
};

if( strpos($img , ".jpg")) $main_img_obj = imagecreatefromjpeg( $img );
if( strpos($img , ".jpeg")) $main_img_obj = imagecreatefromjpeg( $img );
if( strpos($img , ".gif")) $main_img_obj = imagecreatefromgif( $img );
if( strpos($img , ".png")) $main_img_obj = imagecreatefrompng( $img );

$watermark_img_obj = imagecreatefrompng("images/watermark.png");
$return_img_obj = $watermark->create_watermark($main_img_obj, $watermark_img_obj, 20);
header('Content-Type: image/jpeg');
header('Content-Disposition: inline; filename=' . $_GET['src']);
imagejpeg($return_img_obj, '', 70);
?>

class_watermark.php:

Код:

<?
class watermark{

function create_watermark( $main_img_obj, $watermark_img_obj, $alpha_level = 100 ) {
$alpha_level/= 100;

$main_img_obj_w= imagesx( $main_img_obj );
$main_img_obj_h= imagesy( $main_img_obj );
$watermark_img_obj_w= imagesx( $watermark_img_obj );
$watermark_img_obj_h= imagesy( $watermark_img_obj );

$main_img_obj_min_x= floor( ( $main_img_obj_w / 2 ) - ( $watermark_img_obj_w / 2 ) );
$main_img_obj_max_x= ceil( ( $main_img_obj_w / 2 ) + ( $watermark_img_obj_w / 2 ) );
$main_img_obj_min_y= floor( ( $main_img_obj_h / 2 ) - ( $watermark_img_obj_h / 2 ) );
$main_img_obj_max_y= ceil( ( $main_img_obj_h / 2 ) + ( $watermark_img_obj_h / 2 ) );


$return_img= imagecreatetruecolor( $main_img_obj_w, $main_img_obj_h );


for( $y = 0; $y < $main_img_obj_h; $y++ ) {
for( $x = 0; $x < $main_img_obj_w; $x++ ) {
$return_color= NULL;


$watermark_x= $x - $main_img_obj_min_x;
$watermark_y= $y - $main_img_obj_min_y;


$main_rgb = imagecolorsforindex( $main_img_obj, imagecolorat( $main_img_obj, $x, $y ) );


if ($watermark_x >= 0 && $watermark_x < $watermark_img_obj_w &&
$watermark_y >= 0 && $watermark_y < $watermark_img_obj_h ) {
$watermark_rbg = imagecolorsforindex( $watermark_img_obj, imagecolorat( $watermark_img_obj, $watermark_x, $watermark_y ) );


$watermark_alpha= round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 );
$watermark_alpha= $watermark_alpha * $alpha_level;


$avg_red= $this->_get_ave_color( $main_rgb['red'],$watermark_rbg['red'],$watermark_alpha );
$avg_green= $this->_get_ave_color( $main_rgb['green'],$watermark_rbg['green'],$watermark_alpha );
$avg_blue= $this->_get_ave_color( $main_rgb['blue'],$watermark_rbg['blue'],$watermark_alpha );


$return_color= $this->_get_image_color( $return_img, $avg_red, $avg_green, $avg_blue );

} else {
$return_color= imagecolorat( $main_img_obj, $x, $y );
}
imagesetpixel( $return_img, $x, $y, $return_color );

}
}


return $return_img;

}


function _get_ave_color( $color_a, $color_b, $alpha_level ) {
return round( ( ( $color_a * ( 1 - $alpha_level ) ) + ( $color_b* $alpha_level ) ) );
}


function _get_image_color($im, $r, $g, $b) {
$c=imagecolorexact($im, $r, $g, $b);
if ($c!=-1) return $c;
$c=imagecolorallocate($im, $r, $g, $b);
if ($c!=-1) return $c;
return imagecolorclosest($im, $r, $g, $b);
}

} 
?>

доработка и написание любых модулей для WebAsyst и Shop-Script
Портфолио: http://www.free-lance.ru/users/Anton_F
ICQ: 259-726-437 \ Skype: Ant_on_f
Mail: shaman_master#list.ru

Неактивен

 

#4 2009-02-24 09:51

rawman
Пользователь

Re: Добавление водяных знаков на картинки товаров

спасибо, буду разбираться

Неактивен

 

#5 2009-02-25 14:19

zavkiev
Пользователь

Re: Добавление водяных знаков на картинки товаров

кто разбереться, раскажите поподробней, не особо разбирающимся

Неактивен

 

#6 2009-02-27 06:09

rawman
Пользователь

Re: Добавление водяных знаков на картинки товаров

поправьте меня если я ошибаюсь...
представленный выше код нужно скрестить с
\public_html\published\SC\html\scripts\get_image.php
и получается что watermark будет наслаиваться на картинке при обращении к ней, т.е. при просмотре.
скажите, когда ЕЩЕ вызывается get_image.php ???

на мой взгляд правильно приклеивать watermark, когда через админку пользователь прикрепляет к товару картинку. Помогите найти это место, плииииз

Отредактированно rawman (2009-02-27 18:15)

Неактивен

 

#7 2009-02-27 08:19

Shaman
Пользователь

Re: Добавление водяных знаков на картинки товаров

ага , а при смене водного знака придется все  картинки перезаливать)) проще уж накладывать знак динамически.
этот скрипт писался под SS но в WA принцип тот же


доработка и написание любых модулей для WebAsyst и Shop-Script
Портфолио: http://www.free-lance.ru/users/Anton_F
ICQ: 259-726-437 \ Skype: Ant_on_f
Mail: shaman_master#list.ru

Неактивен

 

#8 2009-02-27 18:13

rawman
Пользователь

Re: Добавление водяных знаков на картинки товаров

не вижу смысла часто менять watermark, попробую сам прикрутить его, раз у разработчиков нет желания этим заниматься, чтоб отрабатывал во время добавления картинки.
есть желающие помочь ?

Неактивен

 

#9 2009-03-12 02:51

KGSH
Пользователь

Re: Добавление водяных знаков на картинки товаров

Очень интерисует тоже возможность наложения водяных знаков, как это сделать в "WebAsyst Shop-Script"?

rawman, если разберешься, подскажи пожалуйста!

Кто готов помочь? Возможна оплата.

Неактивен

 

#10 2009-03-13 10:19

SerB
Пользователь

Re: Добавление водяных знаков на картинки товаров

Сколько готовы заплатить за такую доработку?

rawman написал:

Чтоб отрабатывал во время добавления картинки.


Icq: 243 37ноль 4одинодин

Неактивен

 

#11 2009-03-16 04:07

rawman
Пользователь

Re: Добавление водяных знаков на картинки товаров

платить не готов, и так много вложил.

Неактивен

 

#12 2009-03-16 06:41

SerB
Пользователь

Re: Добавление водяных знаков на картинки товаров

Добавляем код class_watermark.php предложенный шаманом например в файл picture_functions.php, или подключаем его. В файле picture_functions.php немного меняем функцию AddNewPictures
        if ($r)
        {
            $new_filename = $_FILES[$filename]["name"];
        $watermark = new watermark();
        $main_img_obj = imagecreatefromjpeg('./products_pictures/'.$new_filename);
        $watermark_img_obj = imagecreatefrompng('./images/watermark.png');
        $return_img_obj = $watermark->create_watermark($main_img_obj, $watermark_img_obj, 66);
        imagejpeg($return_img_obj, './products_pictures/'.$new_filename, 50);
            SetRightsToUploadedFile( "./products_pictures/".$new_filename );
        }
Это для первой картинки, по аналогии для превью и увеличенной картинки делается если нужно. Соответственно сама картинка с водяным знаком вот где лежит "./images/watermark.png"


Icq: 243 37ноль 4одинодин

Неактивен

 

#13 2009-03-29 14:55

Jan
Пользователь

Re: Добавление водяных знаков на картинки товаров

У кого-то реально получилось прикрутить вышеописанный код?

Неактивен

 

#14 2009-11-11 10:44

StaNislav
Пользователь

Re: Добавление водяных знаков на картинки товаров

В последней версии SC на сегодняшний день - есть функция добавления ватермарка, но по заявлению службы поддержки она использоваться не будет в таком виде в каком представлена. Но активировать ее можно измением php кода.


некоторые заметки о  WebAsyst Shop-Script можно почитать в блоге

Неактивен

 

#15 2009-11-11 11:27

kibaka
Пользователь

Re: Добавление водяных знаков на картинки товаров

ребят а можно поподробнее пожалуйста ... А то я не очень шарю во всяких переменных. Какой код поменять на какой и.т.д  Спасибо.

Неактивен

 

#16 2009-11-30 03:53

Allo-osa
Пользователь

Re: Добавление водяных знаков на картинки товаров

это скрипт безвозвратного наложения ватермарки или скрипт который накладывает отпечаток при обращении к картинки, и потом можно скачать по фтп девственно чистые картинки???

Неактивен

 

#17 2009-11-30 06:24

StaNislav
Пользователь

Re: Добавление водяных знаков на картинки товаров

то что привел Шаман - это при обращении


некоторые заметки о  WebAsyst Shop-Script можно почитать в блоге

Неактивен

 

#18 2010-02-09 03:27

REMniOFF
Пользователь

Re: Добавление водяных знаков на картинки товаров

Ребята! А хостер по попке не настучит за такую нагрузку на сервер при динамическом добавлении вотермарка?

Скрипт и так еле скрипит, формирование страниц занимает очень большое время, а тут ещё и такая фича. Не проще пакетно залить фото с водяными знаками, а оригиналы оставить у себя на компе?


Основа всякой мудрости есть терпение — Платон
http://seo-russian.ru

Неактивен

 

#19 2010-03-13 04:55

2825435
Пользователь

Re: Добавление водяных знаков на картинки товаров

REMniOFF написал:

Ребята! А хостер по попке не настучит за такую нагрузку на сервер при динамическом добавлении вотермарка?

Скрипт и так еле скрипит, формирование страниц занимает очень большое время, а тут ещё и такая фича. Не проще пакетно залить фото с водяными знаками, а оригиналы оставить у себя на компе?

Не настучит если будет накладываться на всплывающее окно, все остальные защищать не стоит, они реально никакой ценности не представляют в виду своего маленького размера.

жду новых комментариев в теме, кто пробовал? что получалось? Как делал?

Неактивен

 

#20 2010-05-22 16:51

Netstar
Пользователь

Re: Добавление водяных знаков на картинки товаров

у меня почему-то в админке выдает ошибку:
404 — Не найдено
Извините, запрашиваемый документ не был найден на сервере: /published/SC/html/scripts/get_image.php
причем этого файла get_image.php просто нет...

Неактивен

 

#21 2010-05-24 04:30

rat
Администратор

Re: Добавление водяных знаков на картинки товаров

Попробуйте отсутствующий восстановить файл из дистрибутива.


Не спеши, а то успеешь.

Неактивен

 

#22 2010-08-18 13:05

kibaka
Пользователь

Re: Добавление водяных знаков на картинки товаров

Пришлось самому порыться и нарыть рабочие скрипты WATERMARK

Полный скрипт файла b_product_settings.php лежит по адресу: published/SC/html/scripts/modules/products/_methods/b_product_settings.php

 

Код:

<?php
include_once DIR_FUNC.'/func.product_settings.php';

class prdsetActions extends ActionsController {

    function save_product(){
        $action_source = $this->__action_source;
        $productID = $this->getData('productID');
        $categoryID = $this->getData('categoryID');
            

        $errors = array();
        $category_need_update = array();

        do{
            /**
             * Product info
             */
            

            $make_slug = false;
            $product = GetProduct($productID);
            if(!isset($product['productID'])||!$product['productID']){

                $productID = prdCreateEmptyProduct();
            }elseif(SystemSettings::is_hosted()&&file_exists(WBS_DIR.'/kernel/classes/class.metric.php')){
                include_once(WBS_DIR.'/kernel/classes/class.metric.php');

                $DB_KEY=SystemSettings::get('DB_KEY');
                $U_ID = sc_getSessionData('U_ID');

                $metric = metric::getInstance();
                $metric->addAction($DB_KEY, $U_ID, 'SC','EDITPRODUCT','ACCOUNT', '');

            }
            if($this->getData('make_slug') && !$this->getData('slug')){

                $this->setData('slug', make_slug(LanguagesManager::ml_getFieldValue('name', $this->getData())));
                $make_slug = $this->getData('slug')!=='';
            }else{

                $this->setData('slug', make_slug($this->getData('slug')));
            }

            $this->setData('productID', $productID);

            $productEntry = new Product();
            $productEntry->loadByID($productID);

            $category_need_update[] = $productEntry->categoryID;
            if($this->getData('categoryID') != $productEntry->categoryID)$category_need_update[] = $this->getData('categoryID');

            $productEntry->loadFromArray($this->getData());
            $productEntry->enabled = !$this->getData('product_invisible');
            $productEntry->ordering_available = $this->getData('ordering_available');
            $productEntry->free_shipping = $this->getData('free_shipping');

            if(intval($productEntry->min_order_amount)<1)$productEntry->min_order_amount = 1;
            $max_i = 50;$_slug = $productEntry->slug;
            while($max_i-- && $make_slug && !$productEntry->__isAvailableSlug($_slug)){
                $_slug = $productEntry->slug.'_'.rand_name(2);
            }
            if(!$max_i){
                $_slug .= '_'.rand_name(2);
            }
            $productEntry->slug = $_slug;
            $res = $productEntry->checkInfo();
            if(PEAR::isError($res))break;
            $isDownloadable = $this->getData('ProductIsProgram');
            if(!$isDownloadable&&$productEntry->eproduct_filename){
                $file_path = DIR_PRODUCTS_FILES.'/'.$productEntry->eproduct_filename;
                if(file_exists($file_path)){
                    $res = Functions::exec('file_remove', array($file_path));
                    if(PEAR::isError($res))break;
                }
                $productEntry->eproduct_filename = '';
            }
            $res = $productEntry->save();
            if(PEAR::isError($res))break;

            /**
             * Tags
             */
            $TagManager = &ClassManager::getInstance('tagmanager');
            /* @var $TagManager TagManager */
            $TagManager->saveTags(TAGGEDOBJECT_PRODUCT, $productID, 'tags', $this->getData());

            /**
             * Related products
             */
            $related_products = $this->getData('related_products');
            db_phquery('DELETE FROM ?#RELATED_PRODUCTS_TABLE WHERE Owner=?', $productID);
            if(is_array($related_products)){
                for ($r = count($related_products)-1;$r>=0;$r--){

                    db_phquery('INSERT INTO ?#RELATED_PRODUCTS_TABLE (productID, Owner) VALUES (?,?)',$related_products[$r], $productID);
                }
            }

            /**
             * Appended categories
             */
            $old_app_cats = catGetAppendedCategoriesToProduct($productID);
            foreach ($old_app_cats as $old_app_cat){

                catRemoveProductFromAppendedCategory($productID, $old_app_cat['categoryID'] );
                catUpdateProductCount($productID, $old_app_cat['categoryID'], -1);
            }

            $appended_categories = $this->getData('appended_categories');
            if(is_array($appended_categories)){
                for ($r = count($appended_categories)-1;$r>=0;$r--){

                    catAddProductIntoAppendedCategory($productID, $appended_categories[$r] );
                    if ( CONF_UPDATE_GCV == '1' )catUpdateProductCount($productID, $appended_categories[$r]);
                }
            }

            /**
             * Upload picture
             */
            if(!intval($this->getData('skip_image_upload'))){
                $res = $this->upload_picture(ACTCTRL_POST);
                if(PEAR::isError($res))break;
            }

            $res = $this->update_pictures_priority(ACTCTRL_POST);
            if(PEAR::isError($res))break;

            /**
             * Extra options
             */
            cfgUpdateOptionValue($productID, scanArrayKeysForID($this->getData(), array( 'option_value_\w{2}', 'option_radio_type' )));

            /**
             * Downloadable options
             */
            if($action_source != ACTCTRL_AJAX){
                $res = $this->upload_file(ACTCTRL_POST);
                if(PEAR::isError($res))break;
            }
            if(LanguagesManager::ml_isEmpty('name', $this->getData())){

                $errors[] = prdset_msg_fill_productname;
                break;
            }

        }while (0);
        if($action_source == ACTCTRL_AJAX){
            if(PEAR::isError($error)){

                Message::raiseAjaxMessage(MSG_ERROR, 0, $error->getMessage());die;
            }
            die;
        }

        if(PEAR::isError($res) || count($errors)){

            $error_message = (PEAR::isError($res)?$res->getMessage():'');
            foreach ($errors as $error){

                $error_message .= '<div>'.translate($error).'</div>';
            }
            if($action_source == ACTCTRL_AJAX){
                Message::raiseAjaxMessage(MSG_ERROR, 0, $error->getMessage());die;
            }else{
                Message::raiseMessageRedirectSQ(MSG_ERROR, 'productID='.$productID.'&categoryID='.$categoryID, $error_message);
            }
        }

        foreach($category_need_update as $_category)
        update_products_Count_Value_For_Categories($_category);
        $sorting = '';
        if(isset($_GET['sort'])){
            $sorting .= '&sort='.$_GET['sort'];
            if(isset($_GET['sort_order'])){
                $sorting .= '&sort_order='.$_GET['sort_order'];
            }
        }
        if($action_source == ACTCTRL_AJAX){
            die;
        }else{
            Message::raiseMessageRedirectSQ(MSG_SUCCESS, 'ukey=categorygoods&productID='.$sorting, 'msg_information_save');
        }
    }

    function upload_file(){

        $product = GetProduct($this->getData('productID'));
        if(!isset($product['productID'])||!$product['productID']){

            $this->setData('productID', prdCreateEmptyProduct());
        }

        checkPath(DIR_PRODUCTS_FILES);
        $Register = &Register::getInstance();
        $FilesVar = &$Register->get(VAR_FILES);
            
        $error = null;
            
        do{

            if(!isset($FilesVar['eproduct_filename']))return ;
            if(!isset($FilesVar['eproduct_filename']['name']))return ;
            if(!$FilesVar['eproduct_filename']['name'])return;

            if($FilesVar['eproduct_filename']['error']){
                switch ($FilesVar['eproduct_filename']['error']){
                    case 1:$error='Target file exceeds maximum allowed size.';break;
                    case 2:$error='Target file exceeds the MAX_FILE_SIZE value specified on the upload form.';break;
                    case 3:$error='Target file was not uploaded completely.';break;
                    case 4:$error='No target file was uploaded.';break;
                    case 6:$error='Missing a temporary folder.';break;
                    case 7:$error='Failed to write target file to disk.';break;
                    case 8:$error='File upload stopped by extension.';break;
                }
                if(isset($error)){
                    return PEAR::raiseError($error);
                }
            }

            $file_name = $FilesVar['eproduct_filename']['name'];
            if(file_exists(DIR_PRODUCTS_FILES.'/'.$file_name))
            $file_name = getUnicFile(2, preg_replace('@\.([^\.]+)$@', '%s.$1', $file_name), DIR_PRODUCTS_FILES);
            if(PEAR::isError($res = File::checkUpload($FilesVar['eproduct_filename']))||
                    PEAR::isError($res = Functions::exec('file_move_uploaded', array($FilesVar['eproduct_filename']["tmp_name"], DIR_PRODUCTS_FILES.'/'.$file_name)))
            ){
            /*$res = Functions::exec('file_move_uploaded', array($FilesVar['eproduct_filename']['tmp_name'], DIR_PRODUCTS_FILES.'/'.$file_name));
            if(PEAR::isError($res)){*/
                $error = $res;break;
            }

            $productEntry = new Product();
            $productEntry->loadFromArray($product);

            if( $productEntry->eproduct_filename!=$file_name && $productEntry->eproduct_filename && file_exists(DIR_PRODUCTS_FILES.'/'.$productEntry->eproduct_filename)){
                
                Functions::exec('file_remove', array(DIR_PRODUCTS_FILES.'/'.$productEntry->eproduct_filename));
            }

            $productEntry->eproduct_filename = $file_name;
            $productEntry->save();

        }while(0);
            
        if($action_source == ACTCTRL_AJAX){
            if(PEAR::isError($error)){

                Message::raiseAjaxMessage(MSG_ERROR, 0, $error->getMessage());die;
            }
            die;
        }else{

            return $error;
        }
    }

    function delete_product(){

        DeleteProduct( $this->getData('productID'));
        RedirectSQ('ukey=categorygoods&productID=');
    }

    function set_default_picture(){

        prdSetProductDefaultPicture( $this->getData('productID'), $this->getData('photoID'));
        die;
    }

    function update_pictures_priority($action_source = ACTCTRL_AJAX){
        $productID = $this->getData('productID');
        $scan_result = scanArrayKeysForID($_POST, 'priority');
        $sql = 'UPDATE ?#PRODUCT_PICTURES SET priority=? WHERE photoID=? AND productID=?';

        foreach ($scan_result as $photo_id=>$scan_info){
            if($scan_info['priority']==0){
                prdSetProductDefaultPicture($productID,$photo_id);
            }
            db_phquery($sql, $scan_info['priority'], $photo_id,$productID);
        }
        if($action_source == ACTCTRL_AJAX){
            Message::raiseAjaxMessage(MSG_SUCCESS, '', 'order_saved');
            die;
        }
    }

    function upload_picture($action_source = ACTCTRL_AJAX){

        

        $Register = &Register::getInstance();
        $FilesVar = &$Register->get(VAR_FILES);
        $FilesPostVar = &$Register->get(VAR_POST);
        $error = null;

        do{


            if(
            isset($FilesPostVar['image_source'])&&
            ($FilesPostVar['image_source'] == 'file')&&
            isset($FilesVar['upload_picture'])&&
            isset($FilesVar['upload_picture']['name'])&&
            strlen($FilesVar['upload_picture']['name'])){
                $file_name = $FilesVar['upload_picture']['name'];
            }elseif(
            isset($FilesPostVar['image_source'])&&
            ($FilesPostVar['image_source'] == 'url')&&
            isset($FilesPostVar['upload_picture_url'])
            &&strlen($FilesPostVar['upload_picture_url'])
            &&($FilesPostVar['upload_picture_url']!='URL')
            &&($FilesPostVar['upload_picture_url']!='http://')){

                $file_info = pathinfo($FilesPostVar['upload_picture_url']);
                $file_name = $file_info['basename'];
            }elseif($action_source == ACTCTRL_AJAX){
                $error = PEAR::raiseError(translate('str_image_not_uploaded'));
                break;
            }else{
                return;
            }

            if(!is_image($file_name)){
                $error = PEAR::raiseError(translate('prdset_msg_onlyimages'));
                break;
            }
            //print $file_name."\n";
            $file_name = xStripSlashesGPC($file_name);
            //print 'stripslashes: '.$file_name."\n";
            $file_name = str_replace('#','',urldecode($file_name));
            //print 'urldecode: '.$file_name."\n";

            if(file_exists(DIR_PRODUCTS_PICTURES.'/'.$file_name))
            $file_name = getUnicFile(2, preg_replace('@\.([^\.]+)$@', '%s.$1', $file_name), DIR_PRODUCTS_PICTURES);

            $orig_file = DIR_TEMP.'/'.getUnicFile(4, '%s', DIR_TEMP);
            if(isset($FilesVar['upload_picture'])&&strlen($FilesVar['upload_picture']['name'])){
                if(PEAR::isError($res = File::checkUpload($FilesVar['upload_picture']))||
                    PEAR::isError($res = Functions::exec('file_move_uploaded', array($FilesVar['upload_picture']["tmp_name"], $orig_file)))
                ){
                /*$res = Functions::exec('file_move_uploaded', array($FilesVar['upload_picture']['tmp_name'], $orig_file));
                if(PEAR::isError($res)){*/
                    $error = $res;
                    break;
                }
            }elseif(isset($FilesPostVar['upload_picture_url'])&&strlen($FilesPostVar['upload_picture_url'])){
                $res = Functions::exec('file_copy', array($FilesPostVar['upload_picture_url'], $orig_file));
                if(PEAR::isError($res)){
                    $error = $res;
                    break;
                }
            }

            $temp_file = DIR_TEMP.'/'.getUnicFile(4, '%s', DIR_TEMP);

            /**
             * Standard picture
             */
            $standard_file_name = $file_name;

            if(file_exists(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name))
            $standard_file_name = getUnicFile(2, preg_replace('@\.([^\.]+)$@', '%s.$1', $file_name), DIR_PRODUCTS_PICTURES);

            if(
            PEAR::isError($res = Functions::exec('img_resize', array($orig_file, CONF_PRDPICT_STANDARD_SIZE, CONF_PRDPICT_STANDARD_SIZE, $temp_file)))
            ||
            PEAR::isError($res = Functions::exec('file_copy', array($temp_file, DIR_PRODUCTS_PICTURES.'/'.$standard_file_name)))
            ){
                $error = $res;
                Functions::exec('file_remove', array($temp_file));
                Functions::exec('file_remove', array($orig_file));
                break;
            }

            /**
             * Thumbnail picture
             */
            $thumbnail_file_name = preg_replace('@\.([^\.]+)$@', '_thm.$1', $file_name);
            if(file_exists(DIR_PRODUCTS_PICTURES.'/'.$thumbnail_file_name))
            $thumbnail_file_name = getUnicFile(2, preg_replace('@\.([^\.]+)$@', '%s.$1', $thumbnail_file_name), DIR_PRODUCTS_PICTURES);

            if(
            PEAR::isError($res = Functions::exec('img_resize', array($orig_file, CONF_PRDPICT_THUMBNAIL_SIZE, CONF_PRDPICT_THUMBNAIL_SIZE, $temp_file)))
            ||
            PEAR::isError($res = Functions::exec('file_copy', array($temp_file, DIR_PRODUCTS_PICTURES.'/'.$thumbnail_file_name)))
            ){
                $error = $res;
                Functions::exec('file_remove', array($temp_file));
                Functions::exec('file_remove', array($orig_file));
                Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name));
                break;
            }

            /**
             * Enlarged picture
             */
            $orig_size = getimagesize($orig_file);
            $standard_size = getimagesize(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name);

            if($orig_size[0]>$standard_size[0] || $orig_size[1]>$standard_size[1]){

                $enlarged_file_name = preg_replace('@\.([^\.]+)$@', '_enl.$1', $file_name);
                if(file_exists(DIR_PRODUCTS_PICTURES.'/'.$enlarged_file_name))
                $enlarged_file_name = getUnicFile(2, preg_replace('@\.([^\.]+)$@', '%s.$1', $enlarged_file_name), DIR_PRODUCTS_PICTURES);

                if(
                PEAR::isError($res = Functions::exec('img_wm', array($orig_file, CONF_PRDPICT_ENLARGED_SIZE, CONF_PRDPICT_ENLARGED_SIZE, $temp_file)))
                ||
                PEAR::isError($res = Functions::exec('file_copy', array($temp_file, DIR_PRODUCTS_PICTURES.'/'.$enlarged_file_name)))
                ){
                    $error = $res;
                    Functions::exec('file_remove', array($temp_file));
                    Functions::exec('file_remove', array($orig_file));
                    Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES.'/'.$enlarged_file_name));
                    Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name));
                    Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES.'/'.$thumbnail_file_name));
                    break;
                }
            }else {

                $enlarged_file_name = '';
            }

            $product = GetProduct($this->getData('productID'));
            if(!isset($product['productID'])||!$product['productID']){
                $this->setData('productID', prdCreateEmptyProduct());
            }
            db_phquery("
                INSERT ?#PRODUCT_PICTURES (productID, filename, thumbnail, enlarged, priority)
                VALUES( ?, ?, ?, ?,?)", $this->getData('productID'), $standard_file_name, $thumbnail_file_name, $enlarged_file_name,$this->getData('upload_picture_priority'));

            /*db_phquery("
             INSERT ?#PRODUCT_PICTURES (productID, filename, thumbnail, enlarged)
             VALUES( ?, ?, ?, ?)", $this->getData('productID'), $standard_file_name, $thumbnail_file_name, $enlarged_file_name);
             */
            global $_RESULT;
            global $DB_KEY;

            $_RESULT['picture']['photoID'] = db_insert_id();
            $_RESULT['picture']['thumbnail_url'] =  URL_PRODUCTS_PICTURES.'/'.$thumbnail_file_name;

            $_RESULT['picture']['thumbnail_picture']['file'] = $thumbnail_file_name;
            $_RESULT['picture']['thumbnail_picture']['size'] =sprintf('%0.0f kB',round(filesize(DIR_PRODUCTS_PICTURES.'/'.$thumbnail_file_name)/1024));
            $_RESULT['picture']['thumbnail_picture']['url'] = URL_PRODUCTS_PICTURES.'/'.$thumbnail_file_name;
            list($_RESULT['picture']['thumbnail_picture']['width'], $_RESULT['picture']['thumbnail_picture']['height']) = getimagesize(DIR_PRODUCTS_PICTURES.'/'.$thumbnail_file_name);

            /*if($this->getData('set_default')){

                prdSetProductDefaultPicture($this->getData('productID'), $_RESULT['picture']['photoID']);
                $_RESULT['picture']['is_default'] = 1;
            }*/

            $_RESULT['picture']['large_picture']['file'] = $standard_file_name;
            $_RESULT['picture']['large_picture']['size'] =sprintf('%0.0f kB',round(filesize(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name)/1024));
            $_RESULT['picture']['large_picture']['url'] = URL_PRODUCTS_PICTURES.'/'.$standard_file_name;
            list($_RESULT['picture']['large_picture']['width'], $_RESULT['picture']['large_picture']['height']) = getimagesize(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name);

            if($enlarged_file_name){
                $_RESULT['picture']['enlarged_picture']['file'] = $enlarged_file_name;
                $_RESULT['picture']['enlarged_picture']['size'] =sprintf('%0.0f kB',round(filesize(DIR_PRODUCTS_PICTURES.'/'.$enlarged_file_name)/1024));
                $_RESULT['picture']['enlarged_picture']['url'] = URL_PRODUCTS_PICTURES.'/'.$enlarged_file_name;
                list($_RESULT['picture']['enlarged_picture']['width'], $_RESULT['picture']['enlarged_picture']['height']) = getimagesize(DIR_PRODUCTS_PICTURES.'/'.$enlarged_file_name);
            }else{
                $_RESULT['picture']['enlarged_picture'] = $_RESULT['picture']['large_picture'];
            }


            $_RESULT['productID'] = $this->getData('productID');
            if(isset($FilesPostVar['set_default'])&&intval($FilesPostVar['set_default'])==1){
                prdSetProductDefaultPicture( $this->getData('productID'), $_RESULT['picture']['photoID']);
            }

            Functions::exec('file_remove', array($temp_file));
            Functions::exec('file_remove', array($orig_file));

        }while(0);
        if($action_source == ACTCTRL_AJAX){
            if(PEAR::isError($error)){

                Message::raiseAjaxMessage(MSG_ERROR, 0, $error->getMessage());die;
            }
            die;
        }else{

            return $error;
        }
    }

    function fix_pictures()
    {
        $error = null;
        do{
            $temp_file = DIR_TEMP.'/'.getUnicFile(4, '%s', DIR_TEMP);
            /**
             * Standard picture
             */
            $standard_file_name = $file_name;

            if(file_exists(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name))
            $standard_file_name = getUnicFile(2, preg_replace('@\.([^\.]+)$@', '%s.$1', $file_name), DIR_PRODUCTS_PICTURES);

            $res = Functions::exec('img_resize', array($orig_file, CONF_PRDPICT_STANDARD_SIZE, CONF_PRDPICT_STANDARD_SIZE, $temp_file));

            if(PEAR::isError($res)){
                $error = $res;break;
            }

            $res = Functions::exec('file_copy', array($temp_file, DIR_PRODUCTS_PICTURES.'/'.$standard_file_name));
            if(PEAR::isError($res)){

                $error = $res;
                Functions::exec('file_remove', array($temp_file));
                break;
            }
            /**
             * Thumbnail picture
             */
            $thumbnail_file_name = preg_replace('@\.([^\.]+)$@', '_thm.$1', $file_name);
            if(file_exists(DIR_PRODUCTS_PICTURES.'/'.$thumbnail_file_name))
            $thumbnail_file_name = getUnicFile(2, preg_replace('@\.([^\.]+)$@', '%s.$1', $thumbnail_file_name), DIR_PRODUCTS_PICTURES);

            $res = Functions::exec('img_resize', array(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name, CONF_PRDPICT_THUMBNAIL_SIZE, CONF_PRDPICT_THUMBNAIL_SIZE, $temp_file));
            if(PEAR::isError($res)){
                $error = $res;break;
            }

            $res = Functions::exec('file_copy', array($temp_file, DIR_PRODUCTS_PICTURES.'/'.$thumbnail_file_name));
            if(PEAR::isError($res)){

                $error = $res;
                Functions::exec('file_remove', array($temp_file));
                Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES.'/'.$standard_file_name));
                break;
            }

            /**
             * Enlarged picture
             */
        }while(0);
        if($action_source == ACTCTRL_AJAX){
            if(PEAR::isError($error)){

                Message::raiseAjaxMessage(MSG_ERROR, 0, $error->getMessage());die;
            }
            die;
        }else{

            return $error;
        }
            
    }

    function delete_picture(){

        DeleteThreePictures($this->getData('photoID'));
        die;
    }

    function main(){
        
        $Register = &Register::getInstance();
        $smarty = &$Register->get(VAR_SMARTY);
        /* @var $smarty Smarty */
        $GetVars = &$Register->get(VAR_GET);

        $productID = isset($GetVars['productID'])? intval($GetVars['productID']): 0;

        $categoryID = isset($GetVars['categoryID'])?intval($GetVars['categoryID']):0;

        if ( $productID != 0 ){

            $product = GetProduct($productID);
        }else{
            if(SystemSettings::is_hosted()){
                $session_id = session_id();
                session_write_close();

                $messageClient = new WbsHttpMessageClient($db_key, 'wbs_msgserver.php');
                $messageClient->putData('action', 'ALLOW_ADD_PRODUCT');
                $messageClient->putData('language',(LanguagesManager::getCurrentLanguage()->iso2));
                $messageClient->putData('session_id',$session_id);
                $res=$messageClient->send();

                session_id($session_id);
                session_start();
            }else{
                $res = false;
            }

            if(!$res||$messageClient->getResult('success')==true){
                if($res&&$messageClient->getResult('msg')!=''){
                    $smarty->assign('MessageBlock',"<div class='comment_block' ><span class='success_message'>".$messageClient->getResult('msg').'</span></div>');
                }

                $product = array();
                $product['categoryID'] = $categoryID;
                $product['enabled'] = 1;
                $product['priority'] = 0;
                $product['ordering_available'] = 1;
                $product['Price'] = 0;
                $product['in_stock'] = 0;
                $product['list_price'] = 0;
                $product['sort_order'] = 0;
                $product['eproduct_available_days'] = 365;
                $product['eproduct_download_times'] = 1;
                $product['weight'] = 0;
                $product['free_shipping'] = 0;
                $product['min_order_amount'] = 1;
                $product['shipping_freight'] = 0;
                $product['classID'] = CONF_DEFAULT_TAX_CLASS == '0'?'null':CONF_DEFAULT_TAX_CLASS;
            }else{
                //TO DO: localize string variable
                Message::raiseMessageRedirectSQ(MSG_ERROR,'?ukey=categorygoods&sort=&sort_dir=&search=&search_value=&categoryID='.$categoryID,$messageClient->getResult('msg')!=''?$messageClient->getResult('msg'):'Max product count ('.$messageClient->getResult('MAX_PRODUCT_COUNT').') exceeded');
            }
        }

        /**
         * Product pictures
         */
        $pictures = GetPictures( $productID );

        foreach ($pictures as $_ind=>$_val){
            if ( file_exists(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['filename']) && trim($pictures[$_ind]['filename']) != '' ){
                $pictures[$_ind]['picture_exists'] = 1;
                list($pictures[$_ind]['picture_width'], $pictures[$_ind]['picture_height']) = getimagesize(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['filename']);
                $pictures[$_ind]['large_picture'] = array('size' => sprintf('%0.0f KB',round(filesize(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['filename'])/1024)),'file' => $pictures[$_ind]['filename'], 'width' => $pictures[$_ind]['picture_width'], 'height' => $pictures[$_ind]['picture_height']);
            }else{
                $pictures[$_ind]['large_picture'] = array('size' => 0,'file' => $pictures[$_ind]['filename'], 'width' => 0, 'height' => 0);
            }
            if ( file_exists(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['enlarged']) && trim($pictures[$_ind]['enlarged']) != '' ){
                $pictures[$_ind]['enlarged_exists'] = 1;
                list($pictures[$_ind]['enlarged_width'], $pictures[$_ind]['enlarged_height']) = getimagesize(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['enlarged']);
                $pictures[$_ind]['enlarged_picture'] = array('size' => sprintf('%0.0f KB',round(filesize(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['enlarged'])/1024)),'file' => $pictures[$_ind]['enlarged'], 'width' => $pictures[$_ind]['enlarged_width'], 'height' => $pictures[$_ind]['enlarged_height']);
            }elseif($pictures[$_ind]['picture_exists'] == 1){
                $pictures[$_ind]['enlarged_exists'] = 1;
                $pictures[$_ind]['enlarged_picture'] = $pictures[$_ind]['large_picture'];
            }else{
                $pictures[$_ind]['enlarged_picture'] = array('size' =>0,'file' => $pictures[$_ind]['enlarged'], 'width' => 0, 'height' => 0);
            }

            if ( file_exists(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['thumbnail'])&& trim($pictures[$_ind]['thumbnail']) != '' ){
                $pictures[$_ind]['thumbnail_exists'] = 1;
                list($pictures[$_ind]['thumbnail_width'], $pictures[$_ind]['thumbnail_height']) = getimagesize(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['thumbnail']);
                $pictures[$_ind]['thumbnail_picture'] = array('size' => sprintf('%0.0f KB',round(filesize(DIR_PRODUCTS_PICTURES.'/'.$pictures[$_ind]['thumbnail'])/1024)),'file' => $pictures[$_ind]['thumbnail'], 'width' => $pictures[$_ind]['thumbnail_width'], 'height' => $pictures[$_ind]['thumbnail_height']);
            }else{
                $pictures[$_ind]['thumbnail_picture'] = array('size' =>0,'file' => $pictures[$_ind]['thumbnail'], 'width' => 0, 'height' => 0);
            }

        }

        if(file_exists(DIR_PRODUCTS_FILES.'/'.$product['eproduct_filename']) && $product['eproduct_filename']!=null )$product['eproduct_exists'] = 1;

        if($productID) {

            $RelatedItems = array();
            $q = db_phquery('SELECT productID FROM ?#RELATED_PRODUCTS_TABLE WHERE Owner=?',$productID);
            while ($r = db_fetch_row($q)){

                $p = db_query('SELECT productID, '.LanguagesManager::sql_prepareField('name').' AS name FROM '.PRODUCTS_TABLE.' WHERE productID='.$r[0]);
                if ($r1 = db_fetch_row($p)){

                    $RelatedItems[] = $r1;
                }
            }
            $smarty->assign('RelatedItemsNumber',count($RelatedItems));
            $smarty->assign('RelatedItems', $RelatedItems);
        }

        if($product['eproduct_filename'] && file_exists(DIR_PRODUCTS_FILES.'/'.$product['eproduct_filename'])){

            $product['eproduct_filesize'] = filesize(DIR_PRODUCTS_FILES.'/'.$product['eproduct_filename']);
            $product['eproduct_filesize_str'] = getDisplayFileSize($product['eproduct_filesize'], 'B');
        }else{
            $product['eproduct_filename'] = '';
        }

        $tagManager = &ClassManager::getInstance('tagmanager');
        /*@var $tagManager tagmanager*/
        $defaultCurrency = &Currency::getDefaultCurrencyInstance();

        $product_category = catGetCategoryById($product['categoryID']);
        $product_category['calculated_path'] = catCalculatePathToCategory($product_category['categoryID']);
        $smarty->assign('product_tags', $tagManager->getObjectTagsStrings(TAGGEDOBJECT_PRODUCT, $productID, 'tags'));
        $smarty->assign('tags_cloud', $tagManager->getTagsCloud('tags', TAGGEDOBJECT_PRODUCT));
        $smarty->assign('pictures',$pictures);
        $smarty->assign('appended_categories', catGetAppendedCategoriesToProduct($productID, true));
        $smarty->assign('eproduct_available_days',array(1,2,3,4,5,7,14,30,180,365));
        $options = cfgGetProductOptionValue( $productID );
        if(count($options)>0)$smarty->assign('options',$options);
        $smarty->assign('core_category', $core_category);
        $smarty->assign('product',$product);
        $smarty->assign('product_category', $product_category);
        $smarty->assign('tax_classes', taxGetTaxClasses());
        $smarty->assign('is',$product['in_stock']);
        $smarty->assign('default_currency', $defaultCurrency->getVars());

        $smarty->assign('admin_sub_dpt', 'product_settings.html');
    }
}

ActionsController::exec('prdsetActions');
?>

Далее второй файл picture_functions.php по адресу: /public_html/published/SC/html/scripts/core_functions/

 

Код:

<?php
// *****************************************************************************
// Purpose    gets pictures by product
// Inputs   $productID - product ID
// Remarks
// Returns    array of item
//                each item consits of
//                "photoID"            - photo ID
//                "productID"            - product ID
//                "filename"            - conventional photo filename
//                "thumbnail"            - thumbnail photo filename
//                "enlarged"            - enlarged photo filename
//                "default_picture"    - 1 if default picture, otherwise 0

 
function GetPictures( $productID )
{
    $sql = "select photoID, productID, filename, thumbnail, enlarged from "
        .PRODUCT_PICTURES." where productID = ".$productID.' ORDER BY priority';
    $q=db_query( $sql );
    $q2 = db_query("select default_picture from ".PRODUCTS_TABLE.
                    " where productID = ".$productID );
    $product = db_fetch_row($q2);
    $default_picture = $product[0];
    $res = array();
    while( $row = db_fetch_row($q) )
    {
        if ( (string)$row["photoID"] == (string)$default_picture )
                $row["default_picture"] = 1;
        else
            $row["default_picture"] = 0;
        $res[] = $row;
    }
    return $res;
}

/**
 * Delete three pictures (filename, thumbnail, enlarged) for product
 *
 * @param int $photoID - identifier is corresponded three pictures ( see PRODUCT_PICTURES table in database_structure.xml )
 * @return PEAR_Error | null
 */
function DeleteThreePictures( $photoID ){

    $q=db_query("select filename, thumbnail, enlarged, productID from ".
            PRODUCT_PICTURES." where photoID=".$photoID );
    if ( $picture=db_fetch_row($q) )
    {
        if ( $picture["filename"]!="" && $picture["filename"]!=null )
            if ( file_exists(DIR_PRODUCTS_PICTURES."/".$picture["filename"]) )
                Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES."/".$picture["filename"]));

        if ( $picture["thumbnail"]!="" && $picture["thumbnail"]!=null )
            if ( file_exists(DIR_PRODUCTS_PICTURES."/".$picture["thumbnail"]) )
                Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES."/".$picture["thumbnail"]));

        if ( $picture["enlarged"]!="" && $picture["enlarged"]!=null )
            if ( file_exists(DIR_PRODUCTS_PICTURES."/".$picture["enlarged"]) )
                Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES."/".$picture["enlarged"]));

        $q1 = db_query("select default_picture from ".PRODUCTS_TABLE." where productID=".$picture["productID"]);
        if ( $product = db_fetch_row($q1) )
        {
            if ( $product["default_picture"] == $photoID )
                db_query("update ".PRODUCTS_TABLE." set default_picture=NULL  where productID=".$picture["productID"] );
        }
        db_query("delete from ".PRODUCT_PICTURES." where photoID=".$photoID );
    }
}



// *****************************************************************************
// Purpose    deletes main picture for product
// Inputs   $photoID - picture ID ( see PRODUCT_PICTURES table )
// Remarks    $photoID identifier is corresponded three pictures ( see PRODUCT_PICTURES
//                table in database_structure.xml ), but this function delelete only thumbnail
//                    picture from server and set thumbnail column value to ''
// Returns    nothing
function DeleteFilenamePicture( $photoID )
{
    $q=db_query("select filename from ".PRODUCT_PICTURES." where photoID=".
                $photoID );
    if ( $filename = db_fetch_row($q) )
    {
        if ( file_exists(DIR_PRODUCTS_PICTURES."/".$filename["filename"]) )
                Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES."/".$filename["filename"]));
        db_query("update ".PRODUCT_PICTURES." set filename=''".
                " where photoID=".$photoID );
    }
}

/**
 * Deletes thumbnail picture for product, but this function delelete only thumbnail picture from server and set thumbnail column value to ''
 *
 * @param int $photoID - identifier is corresponded three pictures ( see PRODUCT_PICTURES table in database_structure.xml )
 * @return PEAR_Error | null
 */
function DeleteThumbnailPicture( $photoID ){

    $photoID = intval($photoID);

    $q=db_query("select thumbnail from ".PRODUCT_PICTURES." where photoID=".$photoID );

    if ( $thumbnail=db_fetch_row($q) ){

        if ( file_exists(DIR_PRODUCTS_PICTURES."/".$thumbnail["thumbnail"]) ){
            $res = Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES."/".$thumbnail["thumbnail"]));
            if(PEAR::isError($res))return $res;
        }

        db_query("update ".PRODUCT_PICTURES." set thumbnail='' where photoID=".$photoID );
    }
}

/**
 * Delete enlarged picture for product
 *
 * @param int $photoID
 * @return PEAR_Error | null
 */
function DeleteEnlargedPicture( $photoID ){

    $photoID = intval($photoID);
    $q=db_query("select enlarged from ".PRODUCT_PICTURES." where photoID={$photoID}" );
    if ( $enlarged=db_fetch_row($q) ){

        if ( file_exists(DIR_PRODUCTS_PICTURES."/".$enlarged["enlarged"]) ){

            $res = Functions::exec('file_remove', array(DIR_PRODUCTS_PICTURES."/".$enlarged["enlarged"]));
            if(PEAR::isError($res))return $res;
        }

        db_query("update ".PRODUCT_PICTURES." set enlarged='' where photoID={$photoID}");
    }
}


// *****************************************************************************
// Purpose    updates filenames
// Inputs   $fileNames array of    items
//                each item consits of
//                    "filename"        - normal picture
//                    "thumbnail"        - thumbnail picture
//                    "enlarged"        - enlarged picture
//                key is picture ID ( see PRODUCT_PICTURES  )
// Remarks
//                if $default_picture == -1 then default picture is not set
// Returns    nothing
function UpdatePictures( $productID, $fileNames, $default_picture )
{
    foreach( $fileNames as $key => $value ){

        db_phquery('UPDATE ?#PRODUCT_PICTURES SET filename=?,thumbnail=?,enlarged=? WHERE photoID=?',$value['filename'],$value['thumbnail'],$value['enlarged'],$key);
    }
    if ( $default_picture != -1 )db_phquery('UPDATE ?#PRODUCTS_TABLE SET default_picture=? WHERE productID=?',$default_picture,$productID);
}



// *****************************************************************************
// Purpose    adds new picture
// Inputs    $filename, $thumbnail, $enlarged - keys of item in $_FILES
//                corresponded to these file names
//            $productID - product ID
//            $default_picture - default picture ID
// Remarks
//            if $new_filename == "" then function does not something
//            if $default_picture == -1 then default picture is set to new inserted
//                    item to PRODUCT_PICTURES
// Returns    nothing
function AddNewPictures( $productID, $filename, $thumbnail, $enlarged, $default_picture ){

    if ( !trim($_FILES[$filename]["name"]) )return ;

    $new_filename="";
    $new_thumbnail="";
    $new_enlarged="";

    if ( $_FILES[$filename]["size"]!=0 && is_image($_FILES[$filename]["name"]) ){

        if(PEAR::isError($res = File::checkUpload($_FILES[$filename]))||
        PEAR::isError($res = Functions::exec('file_move_uploaded', array($_FILES[$filename]["tmp_name"], DIR_PRODUCTS_PICTURES."/".$_FILES[$filename]["name"])))
        ){
            return $res;
        }

        $new_filename = $_FILES[$filename]["name"];
        SetRightsToUploadedFile( DIR_PRODUCTS_PICTURES."/".$new_filename );
    }

    if ( $_FILES[$thumbnail]["size"]!=0  && is_image($_FILES[$thumbnail]["name"])){

        $res = Functions::exec('file_move_uploaded', array($_FILES[$thumbnail]["tmp_name"], DIR_PRODUCTS_PICTURES."/".$_FILES[$thumbnail]["name"]));
        if (PEAR::isError($res))return $res;

        $new_thumbnail=$_FILES[$thumbnail]["name"];
        SetRightsToUploadedFile( DIR_PRODUCTS_PICTURES."/".$new_thumbnail );
    }

    if ( $_FILES[$enlarged]["size"]!=0  && is_image($_FILES[$enlarged]["name"])){

        $res = Functions::exec('file_move_uploaded', array($_FILES[$enlarged]["tmp_name"], DIR_PRODUCTS_PICTURES."/".$_FILES[$enlarged]["name"]));
        if (PEAR::isError($res))return $res;

        $new_enlarged=$_FILES[$enlarged]["name"];
        $file = DIR_PRODUCTS_PICTURES."/".$new_enlarged;
        $file2 = DIR_PRODUCTS_PICTURES."/".$new_enlarged.'jpg';
        $result = create_watermark_from_string(
               $file,
               $file,
                'Copyrights (c) 2008',
                'arial.ttf',
                14,
                'CCCCCC',
                75,
                0,
                32
                );
        SetRightsToUploadedFile( DIR_PRODUCTS_PICTURES."/".$new_enlarged );

    }

    if ( $new_filename!="" ){

        db_phquery("
            INSERT ?#PRODUCT_PICTURES (productID, filename, thumbnail, enlarged)
            VALUES( ?, ?, ?, ?)", $productID, $new_filename, $new_thumbnail, $new_enlarged);

        if ( $default_picture == -1 ){

            db_phquery("UPDATE ?#PRODUCTS_TABLE SET default_picture=? WHERE productID=?", db_insert_id(), $productID);
        }
    }
}


// *****************************************************************************
// Purpose    gets thumbnail file name
// Inputs    $productID - product ID
// Remarks
// Returns    file name, it is not full path
function GetThumbnail($productID)
{
    $q=db_query( "select default_picture from ".PRODUCTS_TABLE.
            " where productID=".$productID );
    if ( $product = db_fetch_row($q) )
    {
        $q2 = db_query("select filename, thumbnail, enlarged from ".PRODUCT_PICTURES.
            " where photoID='".$product["default_picture"]."' and productID=".$productID);
        if ( $picture=db_fetch_row($q2) )
        {
            if ( file_exists(DIR_PRODUCTS_PICTURES."/".$picture["thumbnail"]) && strlen($picture["thumbnail"])>0 )
                return $picture["thumbnail"];
            else if ( file_exists(DIR_PRODUCTS_PICTURES."/".$picture["filename"]) && strlen($picture["filename"])>0 )
                return $picture["filename"];
        }
        else //default picture is not defined - get one of the pics if there are any
        {

            $q2 = db_query( "select filename, thumbnail, enlarged from ".PRODUCT_PICTURES." where productID=".$productID );
            if ( $picture=db_fetch_row($q2) )
            {
                if ( file_exists(DIR_PRODUCTS_PICTURES."/".$picture["thumbnail"]) && strlen($picture["thumbnail"])>0 )
                    return $picture["thumbnail"];
                if ( file_exists(DIR_PRODUCTS_PICTURES."/".$picture["filename"]) && strlen($picture["filename"])>0 )
                    return $picture["filename"];
            }

        }
    }
    return "";
}

function shrink_size($src_width, $src_height, $width, $height ){

    if ( $src_width > $src_height && $src_width > $width ){

        $ratio = $src_width/$src_height;
        $height /= $ratio;
    }elseif( $src_height > $height ) {

        $ratio = $src_height/$src_width;
        $width /= $ratio;
    }
    if($src_height < $height || $src_width < $width){
        $width = $src_width;
        $height = $src_height;
    }
    return array(round($width, 0), round($height, 0));
}

class ns_image{

    function read($fileName, &$info){

      $info = @getimagesize($fileName);
      if (!$info) return FALSE;
      switch ($info[2]) {
          case 1:
              // Create recource from gif image
            $srcIm = @imagecreatefromgif( $fileName );
              break;
          case 2:
              // Create recource from jpg image
            $srcIm = @imagecreatefromjpeg( $fileName );
              break;
          case 3:
              // Create resource from png image
            $srcIm = @imagecreatefrompng( $fileName );
              break;
          case 5:
              // Create resource from psd image
              break;
          case 6:
              // Create recource from bmp image imagecreatefromwbmp
            $srcIm = @imagecreatefromwbmp( $fileName );
              break;
          case 7:
              // Create resource from tiff image
              break;
          case 8:
              // Create resource from tiff image
              break;
          case 9:
              // Create resource from jpc image
              break;
          case 10:
              // Create resource from jp2 image
              break;
          default:
              break;
      }

      if (!$srcIm) return FALSE;
      else return $srcIm;
    }

    function resize($file, $width, $height, $destination_file = null,$watermark_file = null,$position = 'right', $alpha_level = 50){
        $width = intval($width);
        $height = intval($height);
        if ( !function_exists('gd_info') )
            return PEAR::raiseError('PHP extension gd not loaded', 1);
//            return PEAR::raiseError(1, 1);

        $src_img = $this->read($file, $info);

        if(!$src_img)
            return PEAR::raiseError('Error read image', 1);
//            return PEAR::raiseError(2, 1);

        if ( !function_exists('imagecreatetruecolor') )
            return PEAR::raiseError('function "imagecreatetruecolor" dosn\'t exists', 1);
//            return PEAR::raiseError(3, 1);

        if ( !function_exists('imagecopyresized') )
            return PEAR::raiseError('function "imagecopyresized" dosn\'t exists', 1);
//            return PEAR::raiseError(4, 1);

        if ( !function_exists('getimagesize') )
            return PEAR::raiseError('function "getimagesize" dosn\'t exists', 1);

        $src_width = imagesx($src_img);
        if(!$width) $width = $src_width;
        $src_height = imagesy($src_img);
        if(!$height) $height = $src_height;
          if ( $src_width > $src_height && $src_width > $width ){

            $ratio = $src_width/$src_height;
            $height /= $ratio;
        }elseif( $src_height > $height ) {

            $ratio = $src_height/$src_width;
            $width /= $ratio;
        }
        
        if($src_height < $height || $src_width < $width){
            $width = $src_width;
            $height = $src_height;
        }
        if($width == $src_width){//skip image resize
            if(($file!=$destination_file)&&!copy($file, $destination_file)){
                return PEAR::raiseError('Error write image', 1);
            }
            return null;
        }

        $dst_img = imagecreatetruecolor( $width, $height );

        if ( !$dst_img ) {
            @imagedestroy( $src_img );
            return PEAR::raiseError( "Error creating true color image {$width}&times;{$height}", 1 );
//            return PEAR::raiseError( 6, 1 );
        }

        if ( function_exists('imagecopyresampled') )
            $res = @imagecopyresampled ( $dst_img, $src_img, 0, 0, 0, 0, $width, $height, $src_width, $src_height );
        else
            $res = @imagecopyresized ( $dst_img, $src_img, 0, 0, 0, 0, $width, $height, $src_width, $src_height );

        if ( !$res ) {
            @imagedestroy( $srcIm );
            @imagedestroy( $destImg );

            return PEAR::raiseError( 'Error copy resized image', 1 );
//            return PEAR::raiseError( 7, 1 );
        }
        
        if(defined('CONF_PICTRESIZE_QUALITY')){
            $quality = intval(constant('CONF_PICTRESIZE_QUALITY'));
            $quality = ($quality>100)?100:(($quality<0)?0:$quality);
        }else{
            $quality = 80;
        }
        //Future add watermark
        $watermark_file = DIR_IMG.'/watermark.png';
        if(false&&$watermark_file && file_exists($watermark_file)){
            $dst_img = $this->addWatermark($dst_img,$watermark_file,$position, $alpha_level);
        }

        $res = @imagejpeg( $dst_img, !is_null($destination_file)?$destination_file:$file, $quality);
        if(!$res)
            return PEAR::raiseError('Error write image', 1);
//            return PEAR::raiseError(8, 1);

        @imagedestroy( $destImg );
        @imagedestroy( $srcIm );
    }


    function wm($file, $width, $height, $destination_file = null,$watermark_file = null,$position = 'right', $alpha_level = 50){

        $width = intval($width);
        $height = intval($height);
        if ( !function_exists('gd_info') )
            return PEAR::raiseError('PHP extension gd not loaded', 1);
//            return PEAR::raiseError(1, 1);

        $src_img = $this->read($file, $info);

        if(!$src_img)
            return PEAR::raiseError('Error read image', 1);
//            return PEAR::raiseError(2, 1);

        if ( !function_exists('imagecreatetruecolor') )
            return PEAR::raiseError('function "imagecreatetruecolor" dosn\'t exists', 1);
//            return PEAR::raiseError(3, 1);

        if ( !function_exists('imagecopyresized') )
            return PEAR::raiseError('function "imagecopyresized" dosn\'t exists', 1);
//            return PEAR::raiseError(4, 1);

        if ( !function_exists('getimagesize') )
            return PEAR::raiseError('function "getimagesize" dosn\'t exists', 1);

        $src_width = imagesx($src_img);
        if(!$width) $width = $src_width;
        $src_height = imagesy($src_img);
        if(!$height) $height = $src_height;
          if ( $src_width > $src_height && $src_width > $width ){

            $ratio = $src_width/$src_height;
            $height /= $ratio;
        }elseif( $src_height > $height ) {

            $ratio = $src_height/$src_width;
            $width /= $ratio;
        }
        
        if($src_height < $height || $src_width < $width){
            $width = $src_width;
            $height = $src_height;
        }
    /*    if($width == $src_width){//skip image resize
            if(($file!=$destination_file)&&!copy($file, $destination_file)){
                //return PEAR::raiseError('Error write image', 1);
            }
            return null;
        } */

        $dst_img = imagecreatetruecolor( $width, $height );

        if ( !$dst_img ) {
            @imagedestroy( $src_img );
            return PEAR::raiseError( "Error creating true color image {$width}&times;{$height}", 1 );
//            return PEAR::raiseError( 6, 1 );
        }

        if ( function_exists('imagecopyresampled') )
            $res = @imagecopyresampled ( $dst_img, $src_img, 0, 0, 0, 0, $src_width, $src_height, $src_width, $src_height );
        else
            $res = @imagecopyresized ( $dst_img, $src_img, 0, 0, 0, 0, $src_width, $src_height, $src_width, $src_height );

        if ( !$res ) {
            @imagedestroy( $srcIm );
            @imagedestroy( $destImg );

            return PEAR::raiseError( 'Error copy resized image', 1 );
//            return PEAR::raiseError( 7, 1 );
        }
        
        if(defined('CONF_PICTRESIZE_QUALITY')){
            $quality = intval(constant('CONF_PICTRESIZE_QUALITY'));
            $quality = ($quality>100)?100:(($quality<0)?0:$quality);
        }else{
            $quality = 80;
        }
        //Future add watermark
        $watermark_file = DIR_IMG.'/watermark.png';
        if($watermark_file && file_exists($watermark_file)){
            $dst_img = $this->addWatermark($dst_img,$watermark_file,'chess', 75);
        }

        $res = @imagejpeg( $dst_img, !is_null($destination_file)?$destination_file:$file, $quality);
        if(!$res)
            return PEAR::raiseError('Error write image', 1);
//            return PEAR::raiseError(8, 1);

        @imagedestroy( $destImg );
        @imagedestroy( $srcIm );
    }
    
    function addWatermark($image,$watermark_file = null,$position = 'right', $alpha_level = 100)
    {
        static $watermark = false;
        static $width;
        static $height;
        if(!$watermark&&$watermark_file){
            if(!$watermark = imagecreatefrompng($watermark_file)){
                return $image;
            }
            $width = imagesx($watermark);
            $height = imagesy($watermark);
        }

        if ( $position == 'right' ) {
            $dest_x = imagesx($image) - $width - 5;
            $dest_y = imagesy($image) - $height - 5;
            imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $width, $height, $alpha_level);
        } elseif ($position == 'chess') {
            $dest_x = intval(imagesx($image)*0.5) - intval($width*0.5);
            $dest_y = intval(imagesy($image)*0.05) - intval($height*0.5);
            $this->imagecopymerge_alpha($image, $watermark, $dest_x, $dest_y, 0, 0, $width, $height, $alpha_level);


            $dest_x = intval(imagesx($image)*0.3) - intval($width*0.5);
            $dest_y = intval(imagesy($image)*0.5) - intval($height*0.5);
            $this->imagecopymerge_alpha($image, $watermark, $dest_x, $dest_y, 0, 0, $width, $height, $alpha_level);


            $dest_x = intval(imagesx($image)*0.5) - intval($width*0.5);
            $dest_y = intval(imagesy($image)*0.95) - intval($height*0.5);
            $this->imagecopymerge_alpha($image, $watermark, $dest_x, $dest_y, 0, 0, $width, $height, $alpha_level);


        } else{
            $dest_x = intval(imagesx($image)*0.5) - intval($width*0.5);
            $dest_y = intval(imagesy($image)*0.5) - intval($height*0.5);
            $this->imagecopymerge_alpha($image, $watermark, $dest_x, $dest_y, 0, 0, $width, $height, $alpha_level);
        }
        return $image;
    }
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    if(!isset($pct)){
        return false;
    }
    $pct /= 100;
    // Get image width and height
    $w = imagesx( $src_im );
    $h = imagesy( $src_im );
    // Turn alpha blending off
    imagealphablending( $src_im, false );
    // Find the most opaque pixel in the image (the one with the smallest alpha value)
    $minalpha = 127;
    for( $x = 0; $x < $w; $x++ )
    for( $y = 0; $y < $h; $y++ ){
        $alpha = ( imagecolorat( $src_im, $x, $y ) >> 24 ) & 0xFF;
        if( $alpha < $minalpha ){
            $minalpha = $alpha;
        }
    }
    //loop through image pixels and modify alpha for each
    for( $x = 0; $x < $w; $x++ ){
        for( $y = 0; $y < $h; $y++ ){
            //get current alpha value (represents the TANSPARENCY!)
            $colorxy = imagecolorat( $src_im, $x, $y );
            $alpha = ( $colorxy >> 24 ) & 0xFF;
            //calculate new alpha
            if( $minalpha !== 127 ){
                $alpha = 127 + 127 * $pct * ( $alpha - 127 ) / ( 127 - $minalpha );
            } else {
                $alpha += 127 * $pct;
            }
            //get the color index with new alpha
            $alphacolorxy = imagecolorallocatealpha( $src_im, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
            //set pixel with the new color + opacity
            if( !imagesetpixel( $src_im, $x, $y, $alphacolorxy ) ){
                return false;
            }
        }
    }
    // The image copy
    imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
} 
    
}

Functions::register(new ns_image(), 'img_resize', 'resize');
Functions::register(new ns_image(), 'img_wm', 'wm');
?>

Далее картинка watermark должна лежать тут: published/publicdata/{Название магазина}/attachments/SC/images/watermark.png

Не забывайте делать Backup !!!

Существует глюк - когда добавляете изображение большого размера и после его открытия на сайте оно не полностью открывается. То есть видно только тот размер который разрешен для отображения WATERMARK.

Очень прошу помочь в решение данного глюка. Спасибо

Неактивен

 

#23 Вчера 17:45

gora4o
Пользователь

Re: Добавление водяных знаков на картинки товаров

У меня не работает. Все сделал так как написано. Сверху на странице просто появляются три каких-то иероглифа, картинки прежние.
Если не тяжело выложите ваши рабочие файлы на файлообменники.


Интернет магазин подарков ручной работы
Уникальные товары каждую неделю
Доставка — по всему миру
Удивите себя и своих друзей!

Неактивен

 

Board footer

Powered by PunBB