如何在php中保存上传图像的比例

时间:2017-05-31 13:57:33

标签: php mysql

我有以下代码,需要在我的脚本中保留上传图像的宽高比:

<?php
ob_start();
session_start();
?>
<?Php
require "includes/config.php";
set_time_limit (0);
$max_file_size=8000; // This is in KB

@$gal_id=$_POST['cat_id'];
@$todo=$_POST['todo'];
$userid=$_SESSION['art_id'];

/// for thumbnail image size //
$n_width=300;
$n_height=300;
$required_image_width=890; // Width of resized image after uploading

if($todo=='upload'){
if(!($gal_id > 0)){
echo "Selectează o categorie ";
exit;
}

while(list($key,$value) = each($_FILES['userfile']['name']))
{
$dt=date("Y-m-d");

$sql=$dbo->prepare("insert into lucrari (cat_id,poza,art_id)      values('$gal_id','$value','$userid')");
if($sql->execute()){
$id=$dbo->lastInsertId();
$file_name=$id."_".$value;
}
else{//echo mysql_error();
echo "O problemă pe server. Contactaţi administratorul! ";
exit;}

$add = $path_upload.$file_name;   // upload directory path is set

copy($_FILES['userfile']['tmp_name'][$key], $add);     //  upload the file to the server

chmod("$add",0777);                 // set permission to the file.

$sql=$dbo->prepare("update lucrari set poza = '$file_name' WHERE lucrare_id=$id");
$sql->execute();

//////////ThumbNail creation //////////////////

if(file_exists($add)){
$tsrc=$path_thumbnail.$file_name;
$im=ImageCreateFromJPEG($add);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
ImageJpeg($newimage,$tsrc);
chmod("$tsrc",0777);
}// end of if
////////Ending of thumb nail ////////

/////////// Resize if width is more than 890 /////

if($required_image_width < $width){
$adjusted_height=round(($required_image_width/$width) * $height);
$im=ImageCreateFromJPEG($add);
$newimage=imagecreatetruecolor($required_image_width,$adjusted_height);
imageCopyResized($newimage,$im,0,0,0,0,$required_image_width,$adjusted_height,$width,$height);
ImageJpeg($newimage,$add);
chmod("$add",0777);
}

echo " &nbsp; <a href=poza.php?lucrare_id=$id target='new'><img src='$tsrc'></a>";
//sleep(5);
}
}

?>

我想要的是编辑此脚本以保留图像的比例,而不是使用:

$n_width=300;
$n_height=300;
发生了什么事     $ n_width = 300;     $ n_height = 300; 在我的情况下,我需要写什么而不是值? 谢谢

1 个答案:

答案 0 :(得分:0)

您需要做的是获得宽高比。例如,480x640肖像图像是3:4,或3/4,或0.75。然后,您需要将最大尺寸(在本例中为640的高度)设置为所需的高度(在您的示例中为300)。然后,您需要将0.75比率(以保持&#34;宽高比&#34;)应用于最小尺寸(宽度480):480 * 0.75 = 360px。

一种记住该做什么的简单方法是,你将大尺寸缩小,最小尺寸甚至更小[乘以它与比例分数]&#34;。 / p>

以下是一些代码来说明我的意思:

<?php
// Set the maximum width and height we want to use
$n_width = 300;
$n_height = 300;

// Get the width to height ratio
$ratio = 0;
// Determine if the image is landscape...
if ($width > $height)
{
    $ratio = $height / $width;
    $n_height *= $ratio;
}
// ...Or portrait
else
{
    $ratio = $width / $height;
    $n_width *= $ratio;
}
?>