1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| <?php
function upload_image($filename,
$destination,
$dst_w = 0,
$dst_h = 0,
$resample = 'basic') {
# Uploading image
# Get image extension
$type = strtolower(substr(strrchr($_FILES[$filename]['name'],"."),1));
if($type == 'jpeg') $type = 'jpg';
if (!preg_match('#^(bmp|gif|jpg|png)$#', $type)) return false;
# Complete destination path
$destination = $destination.'.'.$type;
$root_destination = $_SERVER["DOCUMENT_ROOT"].$destination;
# Create image path folders
@mkdir(preg_replace('#^(.*)/(.*?)$#', '$1', $root_destination), 0755, true);
# Save image
if (!move_uploaded_file($_FILES[$filename]['tmp_name'], $root_destination))
return false;
# Resizing image
if ($dst_h <= 0 && $dst_w <= 0) return $destination;
$src_image = $root_destination;
$dst_image = $root_destination;
# Set defaults and meta
list($src_w, $src_h) = getimagesize($src_image);
$dst_x = 0;
$dst_y = 0;
$src_x = 0;
$src_y = 0;
$dst_w = ($dst_w <= 0) ? $src_w : $dst_w;
$dst_h = ($dst_h <= 0) ? $src_h : $dst_h;
# Load image to memory according to type
switch ($type) {
case 'bmp': $src_image = imagecreatefromwbmp($src_image); break;
case 'jpg': $src_image = imagecreatefromjpeg($src_image); break;
case 'gif': $src_image = imagecreatefromgif($src_image); break;
case 'png': $src_image = imagecreatefrompng($src_image); break;
default: return false;
}
# This is the resizing/resampling/transparency-preserving magic
$res_image = imagecreatetruecolor( $dst_w, $dst_h );
if ($type == "gif" or $type == "png") {
imagecolortransparent($res_image, imagecolorallocatealpha($res_image, 0, 0, 0, 127));
imagealphablending($res_image, false);
imagesavealpha($res_image, true);
}
# Set fill
if ($resample == 'fill') {
if($dst_w == 0) $k = $dst_h/$src_h;
elseif ($dst_h == 0) $k = $dst_w/$src_w;
else $k = min($dst_w/$src_w, $dst_h/$src_h);
$dst_x = ($dst_w - round($src_w * $k)) / 2;
$dst_w = $dst_w - $dst_x * 2;
$dst_y = ($dst_h - round($src_h * $k)) / 2;
$dst_h = $dst_h - $dst_y * 2;
}
imagecopyresampled($res_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
# Write image according to type to the output destination
switch($type){
case 'bmp': imagewbmp($res_image, $dst_image); break;
case 'gif': imagegif($res_image, $dst_image); break;
case 'jpg': imagejpeg($res_image, $dst_image); break;
case 'png': imagepng($res_image, $dst_image); break;
}
return $destination;
}
# ====================================
# TEST
# ====================================
upload_image('image', "/img/image", '300', '200', 'fill');
?> |
Partager