如何用PHP修剪图像?

时间:2015-09-01 07:48:54

标签: php

这是我的index.php文件,我已将图像从tmp文件夹上传并移动到图像文件夹,并且它正常工作。但现在我想在显示器上修剪图像,每张图片应该显示相同的尺寸,我已经尝试了很多方法,但它不起作用。 需要帮助!!

<?php
require_once('appvars.php');
include 'db_connect.php';

$sql = "SELECT * FROM gitarwar";
$data = mysqli_query($dbc, $sql);

echo "<table>";
while ($row = mysqli_fetch_array($data)) 
{
    echo '<tr><td>';
    echo '<strong>' . $row['Score'] . '</strong><br/>';
    echo '<strong>Name:</strong>' . $row['Name'] . '<br/>';
    echo '<strong>Datetime:</strong>' . $row['Datetime'] . '<br/>';
    echo '<img src="' .GW_UPLOADPATH . $row['Screenshot'] . '"  alt="Score image" />';
    echo "</tr>";
}
echo"</table>";
mysqli_close($dbc);
?>

2 个答案:

答案 0 :(得分:1)

我之前有过类似的任务。我的工作是检查图片,如果图片小于$newWidth$newHeight,则会添加。

$imageUrl = [PATH OR URL TO YOUR IMAGE FILE];

$imageContent = file_get_contents($imageUrl);
$im = imagecreatefromstring($imageContent);
$width = imagesx($im);
$height = imagesy($im);

$newwidth = 300;
$newheight = 300;

$output = imagecreatetruecolor($newwidth, $newheight);

imagealphablending($output, false);
$transparency = imagecolorallocatealpha($output, 0, 0, 0, 127);
imagefill($output, 0, 0, $transparency);
imagesavealpha($output, true);

imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);

//Show the image
header('Content-Type: image/png');
imagepng($output); //You can save it with another parameter what is a path
imagedestroy($output);
imagedestroy($im);

您需要更改此行:

imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);

达到你的体型。

实际上并不完全是你想要的,但它可能是一个很好的起点。

答案 1 :(得分:0)

使用imagecreatefrom(jpeg|png|gif)功能可以在上传图像时修剪图像。

$file = "images/" . $_FILES['image']['name'];
$tmp_file = $_FILES['image']['tmp_name'];
$type = $_FILES['images']['type'];
if (move_uploaded_file($tmp_file, $file)) {
        chmod($file, 0777);
        // check the type of image, you can do this for other types too, just change the imagecreatefrom function to the type you want to save the image as
        if ($type === 'image/jpeg') {
            $jpeg = imagecreatefromjpeg($file);
            $jpeg_width = imagesx($jpeg);
            $jpeg_height = imagesy($jpeg);
            $new_width = imagesx($jpeg) / 4;          // Fix the width of the thumb nail images, change the width of image here
            $new_height = imagesy($jpeg) / 4; // change the height of image here

            //new image
            $new_image = imagecreatetruecolor($new_width, $new_height);
            imagecopyresampled($new_image, $jpeg, 0, 0, 0, 0, $new_width, $new_height, $jpeg_width, $jpeg_height);
            imagejpeg($new_image, $thumb);
            chmod($thumb, 0777);
        }
    }