Skip to content

Instantly share code, notes, and snippets.

@kissarat
Created March 31, 2013 00:07
Show Gist options
  • Save kissarat/5278915 to your computer and use it in GitHub Desktop.
Save kissarat/5278915 to your computer and use it in GitHub Desktop.
<?php //phpinfo();exit; ?>
<!DOCTYPE HTML>
<html>
<body>
<?php
if (!isset($_FILES['file']))
goto render;
class File {
protected $filename;
public function __construct($filename) {
$this->filename = $filename;
}
}
class Image {
}
class ImageFile extends File {
protected $metadata;
protected static $loaders = array(
'image/jpeg' => 'imagecreatefromjpeg',
'image/png' => 'imagecreatefrompng',
'image/gif' => 'imagecreatefromgif',
);
public function __construct($filename) {
parent::__construct($filename);
}
public function __get($name) {
if (!$this->metadata)
$this->metadata = getimagesize($this->filename);
switch($name) {
case 'width':
return $this->metadata[0];
case 'height':
return $this->metadata[1];
default:
throw new InvalidArgumentException($name);
}
}
}
$maxWidth = 900;
$maxHeight = 1200;
$maxIconWidth = 200;
$maxIconHeight = 400;
$file = $_FILES['file'];
if (!is_uploaded_file($file['tmp_name']))
die('Зображення не завантажилось');
//move_uploaded_file($file['tmp_name'], $imageFilename);
function limitImageSize($source, $maxWidth, $maxHeight) {
$metadata = stream_get_meta_data($source);
list($width, $height) = getimagesize($metadata['uri']);
$ratio = $width / $height;
if ($ratio > 1) {
if ($width < $maxWidth)
$width = $maxWidth;
$height = (int) round($width / $ratio);
}
else {
if ($height < $maxHeight)
$height = $maxHeight;
$width = (int) round($height * $ratio);
}
return each($width, $height);
}
function resize($source, $dstFilename, $dstWidth, $dstHeight) {
$metadata = stream_get_meta_data($source);
list($srcWidth, $srcHeight) = getimagesize($metadata['uri']);
list($dstWidth, $dstHeight) =
limitImageSize($source, $dstWidth, $dstHeight);
$destination = imagecreatetruecolor($dstWidth, $dstHeight);
imagecopyresized($source, $destination, 0, 0, 0, 0,
$srcWidth, $srcHeight, $dstWidth, $dstHeight);
imagejpeg($destination, $dstFilename);
}
if (!isset($loaders[$file['type']]))
die('Unsupported image type ' + $file['type']);
$imagePath = './files/';
$imageFilename = $imagePath . $file['name'];
$iconFilename = $imagePath . 'icon/' . $file['name'];
$loader = $loaders[$file['type']];
$source = $loader($file['tmp_name']);
resize($source, $imageFilename, $maxWidth, $maxHeight);
resize($source, $iconFilename, $maxIconWidth, $maxIconHeight);
unlink($file['tmp_name']);
render:
?>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<label><?=ini_get('upload_max_filesize') ?></label>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>
<input type="file" name="file" />
<input type="submit" value="Upload" />
<?php end: ?>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment