試著上傳一張照片看看吧
HTML
<form id="upload-form" action="crop.php" method="POST" enctype="multipart/form-data">
<input type="file" name="aafile"/>
<button type="submit" id="save-pic" class="btn btn-primary btn-large">上傳圖片</button>
</form>
PHP
<?php
$file = 'aafile';
$id = 5;
$upload_dir = './';
$output_size = array(
'background'=>array('output_w'=>720, 'output_h'=>1360),
'thumb'=>array('output_w'=>100, 'output_h'=>80)
);
if (isset($_FILES[$file])){
if(is_uploaded_file($_FILES[$file]['tmp_name'])){
centerCropSave($file,$upload_dir,$id,$output_size);
}
}
function centerCropSave($file, $upload_dir, $id, $output_size){
$fileSource = $_FILES[$file];
$fileExt = $fileSource['type'];
if($fileExt == 'image/jpeg'){
$fileType=".jpg";
}elseif($fileExt == 'image/gif'){
$fileType=".gif";
}elseif($fileExt == 'image/png'){
$fileType=".png";
}else{
exit;
}
if($fileType == ".jpg"){
$src = imagecreatefromjpeg($fileSource['tmp_name']);
}elseif($fileType == ".gif"){
$src = imagecreatefromgif($fileSource['tmp_name']);
}elseif($fileType == ".png"){
$src = imagecreatefrompng($fileSource['tmp_name']);
}
//轉向?
$exif = exif_read_data($fileSource['tmp_name']);
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$src = imagerotate($src, 180, 0);
break;
case 6:
$src = imagerotate($src, -90, 0);
break;
case 8:
$src = imagerotate($src, 90, 0);
break;
}
}
//取得來源圖片長寬
$src_w = imagesx($src);
$src_h = imagesy($src);
foreach ($output_size as $dir_key => $dir_value) {
$photo_dir = $upload_dir.$dir_key;
$output_w = $dir_value['output_w'];
$output_h = $dir_value['output_h'];
$src_ratio = $src_w / $src_h;
$output_ratio = $output_w / $output_h;
if ( $src_ratio > $output_ratio ){
// Triggered when source image is wider
$temp_height = $output_h;
$temp_width = ( int ) ( $output_h * $src_ratio );
} else {
// Triggered otherwise (i.e. source image is similar or taller)
$temp_width = $output_w;
$temp_height = ( int ) ( $output_w / $src_ratio );
}
// Resize the image into a temporary GD image
$temp_gdim = imagecreatetruecolor( $temp_width, $temp_height );
imagecopyresampled(
$temp_gdim,
$src,
0, 0,
0, 0,
$temp_width, $temp_height,
$src_w, $src_h
);
// Copy cropped region from temporary image into the desired GD image
$x0 = ( $temp_width - $output_w ) / 2;
$y0 = ( $temp_height - $output_h ) / 2;
$desired_gdim = imagecreatetruecolor( $output_w, $output_h );
imagecopy(
$desired_gdim,
$temp_gdim,
0, 0,
$x0, $y0,
$output_w, $output_h
);
imagejpeg($desired_gdim, $photo_dir.'/'.$id.'.jpg', 100);
//echo $photo_dir.'/'.$id.'.jpg<br/>';
//echo '<img src="'.$photo_dir.'/'.$id.'.jpg"/>';
//echo '<hr/>';
}
}
?>