wikipoints/ground/classes/Image.php

108 lines
2.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
class Image
{
/**
*
* @param string $path
* @return mix string-base64 or false
*/
public static function toBase64($path)
{
if ($path)
{
$type = pathinfo($path, PATHINFO_EXTENSION);
if (!$type)
{
return FALSE;
}
$data = file_get_contents($path);
return $data ? 'data:image/' . $type . ';base64,' . base64_encode($data) : FALSE;
}
return FALSE;
}
/**
* Ресайзит изображение. На входе запрос вида sizeX_sizeY_imgName.ext
* @param type $name
*/
public static function resize($imgName, $sizeX, $sizeY = false, $quality = 85)
{
$dir = 'photos/';
$newDir = 'photos/resize/';
$sizeY = $sizeY ? $sizeY : $sizeX;
$oldImgName = $dir . $imgName;
$newImgName = $newDir . $sizeX . '_' . $sizeY . '_' . $imgName;
if (file_exists($newImgName) || self::imgResize($oldImgName, $newImgName, $sizeX, $sizeY, $quality))
{
return '/' . $newImgName;
}
return '/' . $oldImgName;
}
/**
* Функция img_resize(): генерация thumbnails
* Параметры:
* $src - имя исходного файла
* $dest - имя генерируемого файла
* $width, $height - ширина и высота генерируемого изображения, в пикселях
* Необязательные параметры:
* $quality - качество генерируемого JPEG, по умолчанию 90; максимальное 100;
*/
private static function imgResize($src, $dest, $width, $height, $quality = 90)
{
if (!file_exists($src))
return false;
$size = getimagesize($src);
if ($size === false)
return false;
// Определяем исходный формат по MIME-информации, предоставленной
// функцией getimagesize, и выбираем соответствующую формату
// imagecreatefrom-функцию.
$format = strtolower(substr($size['mime'], strpos($size['mime'], '/') + 1));
$icfunc = "imagecreatefrom" . $format;
if (!function_exists($icfunc))
return false;
$x_ratio = $width / $size[0];
$y_ratio = $height / $size[1];
$ratio = max($x_ratio, $y_ratio);
$use_x_ratio = ($x_ratio == $ratio);
$new_width = $use_x_ratio ? $width : floor($size[0] * $ratio);
$new_height = !$use_x_ratio ? $height : floor($size[1] * $ratio);
$new_left = $use_x_ratio ? 0 : floor(($width - $new_width) / 2);
$new_top = !$use_x_ratio ? 0 : floor(($height - $new_height) / 2);
$isrc = $icfunc($src);
$idest = imagecreatetruecolor($width, $height);
imagefill($idest, 0, 0, 0xFFFFFF);
imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0, $new_width, $new_height, $size[0], $size[1]);
//$iofunct = "image".$format;
//$iofunct($idest, $dest, $quality);
imagejpeg($idest, $dest, $quality);
imagedestroy($isrc);
imagedestroy($idest);
return true;
}
}