2009-12-25 3 views
0

Мне предоставлен код, который может изменять размер/перевыравнивать изображения с URL-адреса. Я хотел бы, чтобы этот код был реализован на моем веб-сайте. Сценарий resample довольно прост, но я действительно не знаю, как заставить его работать с остальной частью веб-сайта. Я действительно надеюсь, что кто-то может помочь мне с этой проблемой.Скрипт Resample, как заставить его работать на существующем веб-сайте с разными URL-адресами img

Код, который производит эскиз состоит в следующем, это часть кода в нижней части этого поста

$img_attributes= 'style="max-height: 100px; max-width: 100px"' . ' title="' . htmlspecialchars($product['product_name']) . '"'; 

Это код, который может ресэмплировать образ:

<?php 
// The file 
$filename = 'http://valplibrary.files.wordpress.com/2009/01/5b585d_merry-christmas-blue-style.jpg'; 
$percent = 0.5; // percentage of resize 

// Content type 
header('Content-type: image/jpeg'); 

// Get new dimensions 
list($width, $height) = getimagesize($filename); 
$new_width = $width * $percent; 
$new_height = $height * $percent; 

// Resample 
$image_p = imagecreatetruecolor($new_width, $new_height); 
$image = imagecreatefromjpeg($filename); 
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

// Output 
imagejpeg($image_p, null, 100); 
?> 

Это весь код, который частично отвечает за thumnails на моем сайте.

<?php 
if(!defined('_VALID_MOS') && !defined('_JEXEC')) die('Direct Access to '.basename(__FILE__).' is not allowed.'); 
/** 
* This is the theme's function file. 
* It allows you to declare additional functions and classes 
* that may be used in your templates 
* 
* @version $Id: theme.php 1427 2008-06-18 20:04:01Z soeren_nb $ 
* @package VirtueMart 
* @subpackage themes 
* @copyright Copyright (C) 2006-2008 soeren - All rights reserved. 
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php 
* VirtueMart is free software. This version may have been modified pursuant 
* to the GNU General Public License, and as distributed it includes or 
* is derivative of works licensed under the GNU General Public License or 
* other free or open source software licenses. 
* See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. 
* 
* http://virtuemart.net 
*/ 
global $mainframe; 

// include the stylesheet for this template 

$vm_mainframe->addScriptDeclaration("window.templatePath = '".JURI::base()."';"); 
$vm_mainframe->addStyleSheet(VM_THEMEURL.'theme.css'); 
$vm_mainframe->addScript(VM_THEMEURL.'theme.js'); 


// Reset of VM defaults JS bits 
define ("_MOOTOOLS_LOADED", "1"); 
define ("_SLIMBOX_LOADED", "1"); 
vmRequest::setVar("usefetchscript", 0, "session"); 

class rokCommonHTML extends vmCommonHTML { 
    function getRokboxImageLink($image_link, $text, $title='', $image_group='') { 
     if($image_group) { 
      $image_group = '('.$image_group.')'; 
     } 

     $img = str_replace(JURI::base(), '', $image_link); 
     if ($img_size = @getimagesize($img)) $size = "[{$img_size[0]} {$img_size[1]}]"; 
     else $size = ""; 
     $link = rokCommonHTML::hyperLink($image_link, $text, '', $title, 'rel="rokbox'.$size.$image_group.'"'); 

     return $link; 
    } 
} 
// End of Reset 

class vmTheme extends vmTemplate { 

    function vmTheme() { 
     parent::vmTemplate(); 

     // Removing this, since we're loading it already from our template 
     //vmCommonHTML::loadMooTools(); 
    } 

    function vmBuildFullImageLink($product) { 
     global $VM_LANG; 

     $product_image = ''; 

     $img_attributes= 'style="max-height: 100px; max-width: 100px"' . ' title="' . htmlspecialchars($product['product_name']) . '"'; 


     /* Wrap the Image into an URL when applicable */ 
     if (@$product["product_url"]) { 
      $product_image = "<a href=\"". $product["product_url"]."\" title=\"".$product['product_name']."\" target=\"_blank\">"; 
      $product_image .= ps_product::image_tag($product['product_thumb_image'], $img_attributes, 0); 
      $product_image .= "</a>"; 
     } 
     /* Show the Thumbnail with a Link to the full IMAGE */ 
     else { 
      if(empty($product['product_full_image'])) { 
       $product_image = "<img src=\"".VM_THEMEURL.'images/'.NO_IMAGE."\" alt=\"".$product['product_name']."\" border=\"0\" />"; 
      } 
      else { 
       // file_exists doesn't work on remote files, 
       // so returns false on remote files 
       // This should fix the "Long Page generation bug" 
       if(file_exists(IMAGEPATH.'product/'.$product['product_full_image'])) { 

        /* Get image width and height */ 
        if($image_info = @getimagesize(IMAGEPATH.'product/'.$product['product_full_image'])) { 
         $width = $image_info[0] + 20; 
         $height = $image_info[1] + 20; 
        } 
       } 
       else { 
        $width = 640; 
        $height= 480; 
       } 
       if(stristr($product['product_full_image'], "http")) { 
        $imageurl = $product['product_full_image']; 
       } 
       else { 
        $imageurl = IMAGEURL.'product/'.rawurlencode($VM_LANG->convert($product['product_full_image'])); 
       } 
       /* Build the "See Bigger Image" Link */ 
       if(@$_REQUEST['output'] != "pdf" && $this->get_cfg('useLightBoxImages', 1)) { 
        $link = $imageurl; 
        $text = ps_product::image_tag($product['product_thumb_image'], $img_attributes, 0)."<br/>".$VM_LANG->_('PHPSHOP_FLYPAGE_ENLARGE_IMAGE'); 

        //$product_image = vmCommonHTML::getLightboxImageLink($link, $text, $product['product_name'], 'product'.$product['product_id']); 
        $product_image = rokCommonHTML::getRokboxImageLink($link, $text, $product['product_name'], 'product'.$product['product_id']); 
       } 
       elseif(@$_REQUEST['output'] != "pdf") { 
        $link = $imageurl; 
        $text = ps_product::image_tag($product['product_thumb_image'], $img_attributes, 0)."<br/>".$VM_LANG->_('PHPSHOP_FLYPAGE_ENLARGE_IMAGE'); 
        // vmPopupLink can be found in: htmlTools.class.php 
        $product_image = vmPopupLink($link, $text, $width, $height); 
       } 
       else { 
        $product_image = "<a href=\"$imageurl\" target=\"_blank\">" 
            . ps_product::image_tag($product['product_thumb_image'], $img_attributes, 0) 
            . "</a>"; 
       } 
      } 
     } 
     return $product_image; 
    } 

    /** 
    * Builds a list of all additional images 
    * 
    * @param int $product_id 
    * @param array $images 
    * @return string 
    */ 
    function vmlistAdditionalImages($product_id, $images, $title='', $limit=1000) { 
     global $sess; 
     $html = ''; 
     $i = 0; 
     foreach($images as $image) { 
      $thumbtag = ps_product::image_tag($image->file_name, 'class="browseProductImage"', 1, 'product', $image->file_image_thumb_width, $image->file_image_thumb_height); 
      $fulladdress = $sess->url('index2.php?page=shop.view_images&amp;image_id='.$image->file_id.'&amp;product_id='.$product_id.'&amp;pop=1'); 

      if($this->get_cfg('useLightBoxImages', 1)) { 
       //$html .= vmCommonHTML::getLightboxImageLink($image->file_url, $thumbtag, $title ? $title : $image->file_title, 'product'.$product_id); 
       $html .= rokCommonHTML::getRokboxImageLink($image->file_url, $thumbtag, $title ? $title : $image->file_title, 'product'.$product_id); 
      } 
      else { 
       $html .= vmPopupLink($fulladdress, $thumbtag, 640, 550); 
      } 
      $html .= ' '; 
      if(++$i > $limit) break; 
     } 
     return $html; 
    } 
    /** 
    * Builds the "more images" link 
    * 
    * @param array $images 
    */ 
    function vmMoreImagesLink($images) { 
     global $mosConfig_live_site, $VM_LANG, $sess; 
     /* Build the JavaScript Link */ 
     $url = $sess->url("index2.php?page=shop.view_images&amp;flypage="[email protected]$_REQUEST['flypage']."&amp;product_id="[email protected]$_REQUEST['product_id']."&amp;category_id="[email protected]$_REQUEST['category_id']."&amp;pop=1"); 
     $text = $VM_LANG->_('PHPSHOP_MORE_IMAGES').'('.count($images).')'; 
     $image = vmCommonHTML::imageTag(VM_THEMEURL.'images/more_images.png', $text, '', '16', '16'); 

     return vmPopupLink($url, $image.'<br />'.$text, 640, 550, '_blank', '', 'screenX=100,screenY=100'); 
    } 


    // Your code here please... 

} 
?> 
+0

Проводка какого-либо образца кода, который вы нашли и спрашивающего нас «сделайте эту работу для меня», просто ленив. Выяснение того, как это работает, будет полезным и полезным для вас, вы никогда не станете хорошим кодером, если попросите других людей сделать вашу работу за вас. – TravisO

+0

Я понимаю, что лично я даже не знаю с чего начать. Я просто не знаю, как это сделать, но спасибо в любом случае. – Chris

ответ

1

Немного Стенка кода МОГ, но придав ему быстрый взгляд, эти два способа делать то, что вы хотите либо иметь сценарий Resample взять имя файла аргумент. Например, в HTML можно поместить

src="resample.php?myjpg.jpg" 

И изменить respamler (Вы должны проверки ошибок, а также, люди могут делать гадости)

<?php 
$filename = 'http://valplibrary.files.wordpress.com/'.key($_GET); 

Другой способ заключается в использовании HTAccess (или альтернатива IIS, если вы не используете Apache), чтобы переписать URL-адреса, что является более аккуратным решением. Создайте папку пальцами и поместить скрипт и файл htacess в.

Используйте файл .htaccess, чтобы соответствовать

http://valplibrary.files.wordpress.com/thumbs/(.*) 

И переписать URL в

resample.php?$1 #(where $1 is the value in (.*)) 

Я надеюсь, что они дают вы идеи.

+0

У меня есть 0,5 понимания php, и это выходит из моей лиги. Можете ли вы объяснить мне, что вам нравится? – Chris

Смежные вопросы