0

我有一个允许 Jpeg 和 PNG 的上传功能。上传图片后,会调用一个 php 文件来处理裁剪函数以裁剪上传的图片。

裁剪图像后,它会以新名称再次保存到服务器。在当前的设置中,只有 jpeg 可以写入服务器。其他任何东西都会绘制黑色图像。我想知道如何编写此代码,以便作物也允许 PNG

处理作物的代码:

$imageLocation = $_SESSION['image_location'];
$newNameOverwrite = $_SESSION['new_name'];

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;

$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
$img_r = imagecreatefromjpeg($src);
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite;

imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);

imagejpeg($dst_r,$name,100); 

$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;

//Thumbnail generate
include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);

$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);

$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}

更新代码:

$imageType = $_SESSION['image_type'];

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$jpeg_quality = 100;

$src = $imageLocation;
list($width, $height, $type, $attr) = getimagesize($src);
$targ_w = $width;
$targ_h = $height;
    if ($imageType == '.jpg' || $imageType == '.jpeg'){
        $img_r = imagecreatefromjpeg($src);
    }
    if ($imageType == '.png'){
        $img_r = imagecreatefrompng($src);
    }       

$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]);
$uploadLocation = 'uploads/';
$name = $uploadLocation.'resized_'.$newNameOverwrite; 

imagecopy(
$dst_r, $img_r,
0, 0, $_POST['x'], $_POST['y'],
$_POST['w'], $_POST['h']
);
var_dump($imageType);
if ($imageType == '.png'){
    imagepng($dst_r,$name); 
}
if ($imageType == '.jpg' || $imageType == '.jpeg'){
    imagejpeg($dst_r,$name, 100); 
    }   
$imageCropped = $name;
$_SESSION['image_cropped'] = $imageCropped;


include('SimpleImage.php');
$imageThumbnail = new SimpleImage();
$imageThumbnail->load($name);
$imageThumbnail->resizeToWidth(200);
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);

$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite);

$imageThumbnailCroppedSession = $imageThumbnailCropped;
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession;
}
4

1 回答 1

1

使用 PHP 来确定它是什么类型的图像,然后动态使用 *_png 函数而不是 *_jpeg 函数。IE,而不是imagecreatefromjpeg使用imagecreatefrompng

于 2013-06-19T14:48:06.013 回答