Exemplo n.º 1
0
function migratePhotos()
{
    $model = cmsCore::getModel('photos');
    $config = cmsConfig::getInstance();
    $photos = $model->orderByList(array(array('by' => 'album_id', 'to' => 'asc'), array('by' => 'date_pub', 'to' => 'asc')))->limit(false)->get('photos', function ($item, $model) {
        $item['image'] = cmsModel::yamlToArray($item['image']);
        return $item;
    });
    if (!$photos) {
        return false;
    }
    $album_ids = $last_photo_id = $order = array();
    foreach ($photos as $photo) {
        $album_ids[] = $photo['album_id'];
        $_order = isset($order[$photo['album_id']]) ? $order[$photo['album_id']] : 1;
        $_widths = $_heights = $sizes = $width_presets = array();
        foreach ($photo['image'] as $preset => $path) {
            if (!is_readable($config->upload_path . $path)) {
                continue;
            }
            $s = getimagesize($config->upload_path . $path);
            if ($s === false) {
                continue;
            }
            $_widths[] = $s[0];
            $_heights[] = $s[1];
            $sizes[$preset] = array('width' => $s[0], 'height' => $s[1]);
            $width_presets[$s[0]] = $preset;
        }
        $order[$photo['album_id']] = $_order + 1;
        $last_photo_id[$photo['album_id']] = $photo['id'];
        // exif
        $max_size_preset = $width_presets[max($_widths)];
        $image_data = img_get_params($config->upload_path . $photo['image'][$max_size_preset]);
        $date_photo = isset($image_data['exif']['date']) ? $image_data['exif']['date'] : false;
        $camera = isset($image_data['exif']['camera']) ? $image_data['exif']['camera'] : null;
        unset($image_data['exif']['date'], $image_data['exif']['camera'], $image_data['exif']['orientation']);
        $photo['slug'] = $model->getPhotoSlug($photo);
        $photo['sizes'] = $sizes;
        $photo['height'] = max($_heights);
        $photo['width'] = max($_widths);
        $photo['ordering'] = $_order;
        $photo['orientation'] = $image_data['orientation'];
        $photo['date_photo'] = $date_photo;
        $photo['camera'] = $camera;
        $photo['exif'] = !empty($image_data['exif']) ? $image_data['exif'] : null;
        $model->filterEqual('id', $photo['id'])->updateFiltered('photos', $photo);
    }
    $album_ids = array_unique($album_ids);
    foreach ($album_ids as $album_id) {
        cmsCache::getInstance()->clean("photos.{$album_id}");
        $model->updateAlbumCoverImage($album_id, array($last_photo_id[$album_id]));
        $model->updateAlbumPhotosCount($album_id);
    }
}
Exemplo n.º 2
0
/**
 * Изменяет размер изображения $src, сохраняя измененное в $dest
 * @param string $src Полный путь к исходному изображению
 * @param string $dest Полный путь куда сохранять измененное изображение
 * @param int $maxwidth Максимальная ширина в px
 * @param int $maxheight Максимальная высота в px
 * @param bool $is_square Создавать квадратное изображение
 * @param int $quality Качество результирующего изображения от 1 до 100
 * @return boolean
 */
function img_resize($src, $dest, $maxwidth, $maxheight = 160, $is_square = false, $quality = 95)
{
    if (!file_exists($src)) {
        return false;
    }
    $upload_dir = dirname($dest);
    if (!is_writable($upload_dir)) {
        @chmod($upload_dir, 0777);
        if (!is_writable($upload_dir)) {
            return false;
        }
    }
    $image_params = img_get_params($src);
    if ($image_params === false) {
        return false;
    }
    $new_width = $image_params['width'];
    $new_height = $image_params['height'];
    // Определяем исходный формат по MIME-информации, предоставленной
    // функцией getimagesize, и выбираем соответствующую формату
    // imagecreatefrom-функцию.
    $format = strtolower(substr($image_params['mime'], strpos($image_params['mime'], '/') + 1));
    $icfunc = 'imagecreatefrom' . $format;
    $igfunc = 'image' . $format;
    if (!function_exists($icfunc)) {
        return false;
    }
    if (!function_exists($igfunc)) {
        return false;
    }
    if ($new_height <= $maxheight && $new_width <= $maxwidth) {
        return copy($src, $dest);
    }
    $isrc = $icfunc($src);
    // автоповорот изображений
    if (isset($image_params['exif']['orientation'])) {
        $actions = array();
        switch ($image_params['exif']['orientation']) {
            case 1:
                break;
            case 2:
                $actions = array('img_flip' => 'x');
                break;
            case 3:
                $actions = array('img_rotate' => -180);
                break;
            case 4:
                $actions = array('img_flip' => 'y');
                break;
            case 5:
                $actions = array('img_flip' => 'y', 'img_rotate' => 90);
                break;
            case 6:
                $actions = array('img_rotate' => 90);
                break;
            case 7:
                $actions = array('img_flip' => 'x', 'img_rotate' => 90);
                break;
            case 8:
                $actions = array('img_rotate' => -90);
                break;
        }
        if ($actions) {
            foreach ($actions as $orient_func => $func_param) {
                $orient_result = $orient_func($func_param, $isrc, $new_width, $new_height);
                $isrc = $orient_result['image_res'];
                $new_width = $image_params['width'] = $orient_result['width'];
                $new_height = $image_params['height'] = $orient_result['height'];
            }
        }
    }
    if ($is_square) {
        $idest = imagecreatetruecolor($maxwidth, $maxwidth);
        if ($format == 'jpeg') {
            imagefill($idest, 0, 0, 0xffffff);
        } else {
            if ($format == 'png' || $format == 'gif') {
                $trans = imagecolorallocatealpha($idest, 255, 255, 255, 127);
                imagefill($idest, 0, 0, $trans);
                imagealphablending($idest, true);
                imagesavealpha($idest, true);
            }
        }
        // вырезаем квадратную серединку по x, если фото горизонтальное
        if ($new_width > $new_height) {
            imagecopyresampled($idest, $isrc, 0, 0, round((max($new_width, $new_height) - min($new_width, $new_height)) / 2), 0, $maxwidth, $maxwidth, min($new_width, $new_height), min($new_width, $new_height));
        }
        // вырезаем квадратную верхушку по y,
        if ($new_width < $new_height) {
            imagecopyresampled($idest, $isrc, 0, 0, 0, 0, $maxwidth, $maxwidth, min($new_width, $new_height), min($new_width, $new_height));
        }
        // квадратная картинка масштабируется без вырезок
        if ($new_width == $new_height) {
            imagecopyresampled($idest, $isrc, 0, 0, 0, 0, $maxwidth, $maxwidth, $new_width, $new_width);
        }
    } else {
        if (!$maxwidth || !$maxheight) {
            $ratio = $new_height / $new_width;
            if (!$maxwidth) {
                $new_height = min($maxheight, $new_height);
                $new_width = $new_height / $ratio;
            } else {
                $new_width = min($maxwidth, $new_width);
                $new_height = $new_width * $ratio;
            }
        } else {
            if ($new_width > $maxwidth) {
                $wscale = $maxwidth / $new_width;
                $new_width *= $wscale;
                $new_height *= $wscale;
            }
            if ($new_height > $maxheight) {
                $hscale = $maxheight / $new_height;
                $new_width *= $hscale;
                $new_height *= $hscale;
            }
        }
        $idest = imagecreatetruecolor($new_width, $new_height);
        if ($format == 'jpeg') {
            imagefill($idest, 0, 0, 0xffffff);
        } else {
            if ($format == 'png' || $format == 'gif') {
                $trans = imagecolorallocatealpha($idest, 255, 255, 255, 127);
                imagefill($idest, 0, 0, $trans);
                imagealphablending($idest, true);
                imagesavealpha($idest, true);
            }
        }
        imagecopyresampled($idest, $isrc, 0, 0, 0, 0, $new_width, $new_height, $image_params['width'], $image_params['height']);
    }
    if ($format == 'jpeg') {
        imageinterlace($idest, 1);
    }
    if ($format == 'png') {
        $quality = 10 - ceil($quality / 10);
    }
    if ($format == 'gif') {
        $quality = NULL;
    }
    // вывод картинки и очистка памяти
    $igfunc($idest, $dest, $quality);
    imagedestroy($isrc);
    imagedestroy($idest);
    return true;
}
Exemplo n.º 3
0
            ?>
</yandex:full-text>
                    <?php 
        }
        ?>
                    <?php 
        if (!empty($feed['mapping']['image'])) {
            ?>
                        <?php 
            $image = cmsModel::yamlToArray($item[$feed['mapping']['image']]);
            ?>
                        <?php 
            if (!empty($image[$feed['mapping']['image_size']])) {
                ?>
                            <?php 
                $imgp = img_get_params($config->upload_path . $image[$feed['mapping']['image_size']]);
                ?>
                            <enclosure url="<?php 
                echo $config->upload_host_abs . '/' . $image[$feed['mapping']['image_size']];
                ?>
" type="<?php 
                echo $imgp['mime'];
                ?>
" length="<?php 
                echo $imgp['filesize'];
                ?>
" />
                        <?php 
            }
            ?>
                    <?php 
Exemplo n.º 4
0
 public function processUpload($album_id)
 {
     $album_id = $album_id ? $album_id : $this->request->get('album_id', 0);
     $album = $this->model->getAlbum($album_id);
     if (!$album) {
         return $this->cms_template->renderJSON(array('success' => false, 'error' => sprintf(LANG_PHOTOS_SELECT_ALBUM, $album['ctype']['labels']['one'])));
     }
     if (!$album['is_public'] && $album['user_id'] != $this->cms_user->id && !$this->cms_user->is_admin) {
         return $this->cms_template->renderJSON(array('success' => false, 'error' => 'access error'));
     }
     // получаем пресеты, которые нужно создать
     $presets = cmsCore::getModel('images')->orderByList(array(array('by' => 'is_square', 'to' => 'asc'), array('by' => 'width', 'to' => 'desc')))->filterIsNull('is_internal')->getPresets();
     if (!$presets || empty($this->options['sizes'])) {
         return $this->cms_template->renderJSON(array('success' => false, 'error' => 'no presets'));
     }
     $result = $this->cms_uploader->upload('qqfile');
     if ($result['success']) {
         if (!$this->cms_uploader->isImage($result['path'])) {
             $result['success'] = false;
             $result['error'] = LANG_UPLOAD_ERR_MIME;
         }
     }
     if (!$result['success']) {
         if (!empty($result['path'])) {
             $this->cms_uploader->remove($result['path']);
         }
         return $this->cms_template->renderJSON($result);
     }
     $result['paths']['original'] = $result['url'];
     foreach ($presets as $p) {
         if (!in_array($p['name'], $this->options['sizes'], true)) {
             continue;
         }
         $path = $this->cms_uploader->resizeImage($result['path'], array('width' => $p['width'], 'height' => $p['height'], 'is_square' => $p['is_square'], 'quality' => $p['is_watermark'] && $p['wm_image'] ? 100 : $p['quality']));
         if (!$path) {
             continue;
         }
         if ($p['is_watermark'] && $p['wm_image']) {
             img_add_watermark($path, $p['wm_image']['original'], $p['wm_origin'], $p['wm_margin'], $p['quality']);
         }
         $result['paths'][$p['name']] = $path;
     }
     $result['filename'] = basename($result['path']);
     // основную exif информацию берём из оригинала
     $image_data = img_get_params($result['path']);
     // если оригинал удаляется, то размеры берём из пресета просмотра на странице
     $big_image_data = img_get_params($this->cms_config->upload_path . $result['paths'][$this->options['preset']]);
     // ориентацию берем из большого фото, т.к. оригиналы автоматически не поворачиваются
     $image_data['orientation'] = $big_image_data['orientation'];
     if (empty($this->options['is_origs'])) {
         @unlink($result['path']);
         unset($result['paths']['original']);
         $image_data['width'] = $big_image_data['width'];
         $image_data['height'] = $big_image_data['height'];
     }
     unset($result['path']);
     // маленкая картинка
     $last_image = end($result['paths']);
     $result['url'] = $this->cms_config->upload_host . '/' . $last_image;
     // большая картинка
     $first_image = reset($result['paths']);
     $result['big_url'] = $this->cms_config->upload_host . '/' . $first_image;
     $sizes = array();
     foreach ($result['paths'] as $name => $relpath) {
         $s = getimagesize($this->cms_config->upload_path . $relpath);
         if ($s === false) {
             continue;
         }
         $sizes[$name] = array('width' => $s[0], 'height' => $s[1]);
     }
     $date_photo = isset($image_data['exif']['date']) ? $image_data['exif']['date'] : false;
     $camera = isset($image_data['exif']['camera']) ? $image_data['exif']['camera'] : null;
     unset($image_data['exif']['date'], $image_data['exif']['camera'], $image_data['exif']['orientation']);
     $result['id'] = $this->model->addPhoto(array('album_id' => $album['id'], 'user_id' => $this->cms_user->id, 'image' => $result['paths'], 'date_photo' => $date_photo, 'camera' => $camera, 'width' => $image_data['width'], 'height' => $image_data['height'], 'sizes' => $sizes, 'is_private' => 2, 'orientation' => $image_data['orientation'], 'exif' => !empty($image_data['exif']) ? $image_data['exif'] : null));
     return $this->cms_template->renderJSON($result);
 }