图像在php中调整大小?

时间:2014-06-17 11:14:16

标签: php css image resize

如何在没有"压缩"的情况下在php中调整比例图像的大小。 ?我需要一些解决方案,我在这里搜索,但我无法找到我需要的东西。 我有什么:

<?php
if (isset($_SESSION['username'])) {
    if (isset($_POST['upload'])) {
        $allowed_filetypes = array('.jpg', '.jpeg', '.png', '.gif');
        $max_filesize      = 10485760;
        $upload_path       = 'gallery/';
        $filename          = $_FILES['userfile']['name'];
        $ext               = substr($filename, strpos($filename, '.'), strlen($filename) - 1);

        if (!in_array($ext, $allowed_filetypes)) {
            die('The file you attempted to upload is not allowed.');
        }

        if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
            die('The file you attempted to upload is too large.');
        }

        if (!is_writable($upload_path)) {
            die('You cannot upload to the specified directory, please CHMOD it to 777.');
        }

        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
            $q = mysqli_query($connection, "UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");
            echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
        } else {
            echo 'There was an error during the file upload.  Please try again.';
        }
    }
    echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';
    echo ' <input type="file" name="userfile"/>';
    echo ' <input type="submit" name="upload"  value="Качи">';
    echo ' </form>';
} else {
    echo "<font color='#ec3f8c'>Съжелявам! За да  качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>";
}
?>

我想添加以下内容:Click here

我怎么称呼图像?

echo '<a href="profiles.php?id='.$rowtwo['id'].'">';
  echo"<img src='gallery/".$rowtwo['avatar']."' width='170px' height='217px'/>"; 
  echo'</a>';

我将用户数据库中的头像图像保存为头像。

4 个答案:

答案 0 :(得分:0)

使用JS要容易得多。它也可以更好地工作,因为你让客户端执行缓慢的操作工作,而不是使用有限的服务器资源来执行该任务。

以下是一个示例:

//This is the URL to your original image
var linkUrl = "http://www.mywebsite.com/myimage.png";
//This is a div that is necessary to trick JS into letting you manipulate sizing
//Just make sure it exists and is hidden
var img = $('#HiddenDivForImg');

//This is a call to the function
image_GetResizedImage(img, linkUrl);

//This function does the magic
function image_GetResizedImage(img, linkUrl) {
    //Set your max height or width dimension (either, not both)
    var maxDim = 330;
    //Define the equalizer to 1 to avoid errors if incorrect URL is given
    var dimEq = 1;

    //This determines if the larger dimension is the images height or width.
    //Then, it divides that dimension by the maxDim to get a decimal number for size reduction
    if (img.height() > maxDim || img.width() > maxDim) {
        if (img.height() > img.width()) {
            dimEq = maxDim / img.height();
        } else {
            dimEq = maxDim / img.width();
        }
    }

    var imageOutput = "<a href='" + linkUrl + "' target='_blank'>View Larger</a><br /><a href='" + result +
        "' target='_blank'><img src='" + linkUrl + "' style='width: " + img.width() * dimEq
        + "px; height: " + img.height() * dimEq + "px' /></a>";

    //This returns a URL for the image with height and width tags of the resized (non-squished) image.
    return imageOutput;
}

答案 1 :(得分:0)

对于PHP中的图像处理,您可以使用Imagemagick。 http://www.imagemagick.org/

它是您正在寻找的缩放命令。

答案 2 :(得分:0)

在这里,我使用您的参考链接创建了一个函数,您可以像这样使用它

将其称为

//Resize uploaded image 
resize_image($_FILES['userfile'], 100, 200);

//Or if you want to save image with diffrent name
$filename = $upload_path.$_SESSION['username'].'-avatar.jpg';
resize_image($_FILES['userfile'], 100, 200, $newfilename);

//if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
        $q = mysqli_query($connection, "UPDATE users SET avatar='".$filename."' WHERE username ='".$_SESSION['username']."'");


        echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
    } else {
        echo 'There was an error during the file upload.  Please try again.';
    }

功能

function resize_image($image_src, $w = 100, $h = 100, $save_as = null) {
    // Create image from file
    switch(strtolower($image_src['type']))
    {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($image_src['tmp_name']);
            break;
        case 'image/png':
            $image = imagecreatefrompng($image_src['tmp_name']);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($image_src['tmp_name']);
            break;
        default:
            exit('Unsupported type: '.$image_src['type']);
    }

    // Target dimensions
    $max_width = $w;
    $max_height = $h;

    // Get current dimensions
    $old_width  = imagesx($image);
    $old_height = imagesy($image);

    // Calculate the scaling we need to do to fit the image inside our frame
    $scale      = min($max_width/$old_width, $max_height/$old_height);

    // Get the new dimensions
    $new_width  = ceil($scale*$old_width);
    $new_height = ceil($scale*$old_height);

    // Create new empty image
    $new = imagecreatetruecolor($new_width, $new_height);

    // Resize old image into new
    imagecopyresampled($new, $image,
        0, 0, 0, 0,
        $new_width, $new_height, $old_width, $old_height);

    if($save_as) {
        //Save as new file 
        imagejpeg($new, $save_as, 90);
    }else{
        //Overwrite image 
        imagejpeg($new, $image_src['tmp_name'], 90);
    }
       // Destroy resources
           imagedestroy($image);
       imagedestroy($new);
}

答案 3 :(得分:0)

我使用http://image.intervention.io/。您可以缩放,缓存,存储,转换和执行各种图像处理任务。

非常好用。

// load the image
$img = Image::make('public/foo.jpg');

// resize the width of the image to 300 pixels and constrain proportions.
$img->resize(300, null, true);

// save file as png with 60% quality
$img->save('public/bar.png', 60);